Skip to content

Your Android phone and your Windows PC, working as one. Local-first, end-to-end encrypted, no account.

Texts on the PC: a Messages page, through the phone

Bee27e1a23d3b16
diff --git a/README.md b/README.md
index 2c7a613..731b86d 100644
--- a/README.md
+++ b/README.md
@@ -89,6 +89,9 @@ place and tested; the user-facing features of Phase 1 come next.
on the phone, share them from any app or pick them in Nectarlink. They land in `Downloads\Nectarlink` on the PC and
`Download/Nectarlink` on the phone, with progress, cancelling, and transfers
that pick up where they left off after a dropped connection.
+- **Texts** on the PC: a Messages page with the phone's conversations
+ (pictures included), to reply or start a new one; texts go out through
+ the phone.
- **Calls**: see who's calling on the PC (with the contact's name and
photo), and answer, decline or silence it from there; the call itself
stays on the phone. Calls nobody answered show as missed.
diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml
index 6c1271a..7552239 100644
--- a/android/app/src/main/AndroidManifest.xml
+++ b/android/app/src/main/AndroidManifest.xml
@@ -27,6 +27,14 @@
<uses-permission android:name="android.permission.READ_CALL_LOG" />
<uses-permission android:name="android.permission.ANSWER_PHONE_CALLS" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
+ <!-- Calls and texts need a phone line, but tablets without one still
+ run everything else. -->
+ <uses-feature
+ android:name="android.hardware.telephony"
+ android:required="false" />
+ <!-- Texts, read and sent from paired PCs (asked for in the app). -->
+ <uses-permission android:name="android.permission.READ_SMS" />
+ <uses-permission android:name="android.permission.SEND_SMS" />
<!-- New photos and screenshots, shown on paired PCs (asked for in the app). -->
<uses-permission android:name="android.permission.READ_MEDIA_IMAGES" />
<uses-permission
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/core/Core.kt b/android/app/src/main/kotlin/app/nectarlink/android/core/Core.kt
index a9e9583..c34e641 100644
--- a/android/app/src/main/kotlin/app/nectarlink/android/core/Core.kt
+++ b/android/app/src/main/kotlin/app/nectarlink/android/core/Core.kt
@@ -18,6 +18,7 @@ import app.nectarlink.android.R
import app.nectarlink.android.notifications.NotificationListener
import app.nectarlink.android.calls.PhoneCalls
import app.nectarlink.android.photos.RecentPhotos
+import app.nectarlink.android.sms.PhoneSms
import app.nectarlink.core.Event
import app.nectarlink.core.EventListener
import app.nectarlink.core.FileToSend
@@ -65,7 +66,11 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListener
phoneMedia,
onLink = { pc, url -> LinkNotifications.show(this.context, _state.value.nameOf(pc).orEmpty(), url) },
onCall = { id, command -> calls.command(id, command) },
+ sms = { sms },
)
+ private val sms = PhoneSms(this.context) {
+ notificationOps.trySend { it.smsChanged(null) }
+ }
private val calls = PhoneCalls(this.context) { call ->
notificationOps.trySend { node ->
runCatching { node.callChanged(call) }.onFailure { Log.i(TAG, "a call wasn't reported", it) }
@@ -143,11 +148,18 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListener
battery.start()
network.start()
}
- _state.update { it.copy(photoAccess = RecentPhotos.hasAccess(context), callAccess = PhoneCalls.hasAll(context)) }
+ _state.update {
+ it.copy(
+ photoAccess = RecentPhotos.hasAccess(context),
+ callAccess = PhoneCalls.hasAll(context),
+ smsAccess = PhoneSms.hasAll(context),
+ )
+ }
started.updatePower(PowerLevel.BASIC, capabilities(NotificationListener.hasAccess(context)))
scope.launch(Dispatchers.Main) {
if (_state.value.photoAccess) photos.start()
calls.start()
+ sms.start()
}
scope.launch {
for (op in notificationOps) {
@@ -190,22 +202,26 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListener
val unrestricted = BackgroundAccess.isUnrestricted(context)
val photoAccess = RecentPhotos.hasAccess(context)
val callAccess = PhoneCalls.hasAll(context)
+ val smsAccess = PhoneSms.hasAll(context)
val photosChanged = photoAccess != _state.value.photoAccess
val callsChanged = callAccess != _state.value.callAccess
+ val smsChanged = smsAccess != _state.value.smsAccess
_state.update {
it.copy(
notificationAccess = granted,
backgroundUnrestricted = unrestricted,
photoAccess = photoAccess,
callAccess = callAccess,
+ smsAccess = smsAccess,
)
}
if (granted && NotificationListener.instance == null) {
NotificationListenerService.requestRebind(NotificationListener.component(context))
}
- if ((photosChanged || callsChanged) && node != null) {
+ if ((photosChanged || callsChanged || smsChanged) && node != null) {
if (photoAccess) photos.start() else photos.stop()
if (PhoneCalls.canFollow(context)) calls.start() else calls.stop()
+ if (PhoneSms.canRead(context)) sms.start() else sms.stop()
notificationOps.trySend { it.updatePower(PowerLevel.BASIC, capabilities(_state.value.notificationAccess)) }
}
}
@@ -336,7 +352,9 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListener
(if (notificationAccess) NOTIFICATION_CAPABILITIES + MEDIA_CAPABILITIES else emptyList()) +
(if (_state.value.photoAccess) PHOTO_CAPABILITIES else emptyList()) +
(if (PhoneCalls.canFollow(context)) listOf("call.state") else emptyList()) +
- (if (PhoneCalls.canControl(context)) listOf("call.control") else emptyList())
+ (if (PhoneCalls.canControl(context)) listOf("call.control") else emptyList()) +
+ (if (PhoneSms.canRead(context)) listOf("sms.read") else emptyList()) +
+ (if (PhoneSms.canSend(context)) listOf("sms.send") else emptyList())
// ---- Pairing ----
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/core/CoreState.kt b/android/app/src/main/kotlin/app/nectarlink/android/core/CoreState.kt
index 9eba398..d4874b5 100644
--- a/android/app/src/main/kotlin/app/nectarlink/android/core/CoreState.kt
+++ b/android/app/src/main/kotlin/app/nectarlink/android/core/CoreState.kt
@@ -62,6 +62,8 @@ data class CoreState(
val ringingFrom: String? = null,
/** Whether the user let Nectarlink read notifications (to mirror them). */
val notificationAccess: Boolean = false,
+ /** Whether the user let Nectarlink read and send texts (for PCs). */
+ val smsAccess: Boolean = false,
/** Whether the user let Nectarlink follow and answer calls (to show them on PCs). */
val callAccess: Boolean = false,
/** Whether the user let Nectarlink see the phone's photos (to show new ones on PCs). */
@@ -113,7 +115,7 @@ data class CoreState(
// Shown in Android's media controls (see media/PcMedia).
is Event.MediaChanged -> this
// PCs only: phones announce their own photos and calls.
- is Event.PhotoAdded, is Event.CallChanged -> this
+ is Event.PhotoAdded, is Event.CallChanged, is Event.SmsChanged -> this
}
private fun withTransfer(transfer: Transfer): List<Transfer> {
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/core/PhonePlatform.kt b/android/app/src/main/kotlin/app/nectarlink/android/core/PhonePlatform.kt
index a5177a6..6e88dd7 100644
--- a/android/app/src/main/kotlin/app/nectarlink/android/core/PhonePlatform.kt
+++ b/android/app/src/main/kotlin/app/nectarlink/android/core/PhonePlatform.kt
@@ -12,7 +12,11 @@ import app.nectarlink.android.clipboard.PhoneClipboard
import app.nectarlink.android.notifications.NotificationListener
import app.nectarlink.android.media.PhoneMedia
import app.nectarlink.android.photos.RecentPhotos
+import app.nectarlink.android.sms.PhoneSms
import app.nectarlink.core.CallCommand
+import app.nectarlink.core.SmsMessage
+import app.nectarlink.core.SmsPartData
+import app.nectarlink.core.SmsThread
import app.nectarlink.core.FileToSend
import app.nectarlink.core.MediaAction
import app.nectarlink.core.NotificationFailure
@@ -30,6 +34,8 @@ internal class PhonePlatform(
private val onLink: (String, String) -> Boolean,
/** Answers, declines or silences a call: (call ID, command) → done. */
private val onCall: (String, CallCommand) -> Boolean,
+ /** The phone's texts (created after this). */
+ private val sms: () -> PhoneSms,
) : Platform {
private val context = context.applicationContext
@@ -51,6 +57,15 @@ internal class PhonePlatform(
override fun callCommand(id: String, command: CallCommand): Boolean = onCall(id, command)
+ override fun smsThreads(limit: UInt): List<SmsThread> = sms().threads(limit.toInt())
+
+ override fun smsMessages(thread: String, before: Long?, limit: UInt): List<SmsMessage> =
+ sms().messages(thread, before, limit.toInt())
+
+ override fun smsSend(to: List<String>, body: String): Boolean = sms().send(to, body)
+
+ override fun smsPart(id: String): SmsPartData? = sms().part(id)
+
override fun dismissNotification(key: String) {
val listener = NotificationListener.instance ?: throw NotificationFailure.Unsupported()
listener.dismiss(key)
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/sms/PhoneSms.kt b/android/app/src/main/kotlin/app/nectarlink/android/sms/PhoneSms.kt
new file mode 100644
index 0000000..620bd42
--- /dev/null
+++ b/android/app/src/main/kotlin/app/nectarlink/android/sms/PhoneSms.kt
@@ -0,0 +1,334 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+package app.nectarlink.android.sms
+
+import android.Manifest
+import android.content.Context
+import android.content.pm.PackageManager
+import android.database.ContentObserver
+import android.database.Cursor
+import android.graphics.Bitmap
+import android.graphics.BitmapFactory
+import android.net.Uri
+import android.os.Build
+import android.os.Handler
+import android.os.Looper
+import android.provider.ContactsContract
+import android.provider.Telephony
+import android.telephony.SmsManager
+import android.util.Log
+import androidx.core.content.ContextCompat
+import app.nectarlink.core.SmsMessage
+import app.nectarlink.core.SmsPart
+import app.nectarlink.core.SmsPartData
+import app.nectarlink.core.SmsThread
+import java.io.ByteArrayOutputStream
+
+/**
+ * The phone's text messages, for PCs (docs/protocol/sms.md): lists
+ * conversations and messages (SMS and MMS), sends texts, and says when
+ * anything changed. Only reads: Android lets only the default SMS app
+ * change the messages store.
+ */
+internal class PhoneSms(context: Context, private val onChange: () -> Unit) {
+ private val context = context.applicationContext
+ private val resolver = context.contentResolver
+ private val handler = Handler(Looper.getMainLooper())
+ private var observer: ContentObserver? = null
+ private val notify = Runnable { onChange() }
+
+ fun start() {
+ if (observer != null || !canRead(context)) return
+ observer = object : ContentObserver(handler) {
+ // Sending or receiving touches several rows: say it once.
+ override fun onChange(selfChange: Boolean) {
+ handler.removeCallbacks(notify)
+ handler.postDelayed(notify, SETTLE_MS)
+ }
+ }.also { resolver.registerContentObserver(Uri.parse("content://mms-sms/"), true, it) }
+ }
+
+ fun stop() {
+ observer?.let { resolver.unregisterContentObserver(it) }
+ observer = null
+ handler.removeCallbacks(notify)
+ }
+
+ // ---- Conversations ----
+
+ fun threads(limit: Int): List<SmsThread> = guarded(emptyList()) {
+ val addresses = canonicalAddresses()
+ val contacts = Contacts()
+ val uri = Uri.parse("content://mms-sms/conversations?simple=true")
+ val columns = arrayOf(
+ Telephony.Threads._ID,
+ Telephony.Threads.DATE,
+ Telephony.Threads.RECIPIENT_IDS,
+ Telephony.Threads.SNIPPET,
+ Telephony.Threads.READ,
+ Telephony.Threads.HAS_ATTACHMENT,
+ )
+ resolver.query(uri, columns, null, null, "${Telephony.Threads.DATE} DESC")?.use { c ->
+ buildList {
+ while (size < limit && c.moveToNext()) {
+ val id = c.getLong(0)
+ val people = c.getString(2).orEmpty().split(' ').mapNotNull { it.toLongOrNull()?.let(addresses::get) }
+ if (people.isEmpty()) continue
+ val names = people.map { contacts.name(it).orEmpty() }
+ val snippet = c.getString(3)?.takeIf { it.isNotBlank() }
+ ?: if (c.getInt(5) != 0) PICTURE_SNIPPET else ""
+ add(
+ SmsThread(
+ id = id.toString(),
+ addresses = people,
+ names = names,
+ snippet = snippet,
+ date = c.getLong(1),
+ unread = if (c.getInt(4) == 0) unreadIn(id) else 0u,
+ photo = people.singleOrNull()?.let(contacts::photo),
+ ),
+ )
+ }
+ }
+ }.orEmpty()
+ }
+
+ private fun unreadIn(thread: Long): UInt =
+ resolver.query(
+ Telephony.Sms.CONTENT_URI,
+ arrayOf(Telephony.Sms._ID),
+ "${Telephony.Sms.THREAD_ID} = ? AND ${Telephony.Sms.READ} = 0",
+ arrayOf(thread.toString()),
+ null,
+ )?.use { it.count.toUInt() } ?: 0u
+
+ /** Recipient IDs (as conversations list them) to numbers. */
+ private fun canonicalAddresses(): Map<Long, String> =
+ resolver.query(Uri.parse("content://mms-sms/canonical-addresses"), arrayOf("_id", "address"), null, null, null)?.use { c ->
+ buildMap { while (c.moveToNext()) c.getString(1)?.let { put(c.getLong(0), it) } }
+ }.orEmpty()
+
+ // ---- Messages ----
+
+ fun messages(thread: String, before: Long?, limit: Int): List<SmsMessage> = guarded(emptyList()) {
+ val threadId = thread.toLongOrNull() ?: return@guarded emptyList()
+ (sms(threadId, before, limit) + mms(threadId, before, limit))
+ .sortedByDescending { it.date }
+ .take(limit)
+ }
+
+ private fun sms(thread: Long, before: Long?, limit: Int): List<SmsMessage> {
+ val columns = arrayOf(
+ Telephony.Sms._ID, Telephony.Sms.ADDRESS, Telephony.Sms.BODY, Telephony.Sms.DATE, Telephony.Sms.TYPE,
+ )
+ val (selection, args) = page(Telephony.Sms.THREAD_ID, Telephony.Sms.DATE, thread, before)
+ return resolver.query(Telephony.Sms.CONTENT_URI, columns, selection, args, "${Telephony.Sms.DATE} DESC")?.use { c ->
+ buildList {
+ while (size < limit && c.moveToNext()) {
+ val type = c.getInt(4)
+ add(
+ SmsMessage(
+ id = "sms:${c.getLong(0)}",
+ thread = thread.toString(),
+ address = c.getString(1).orEmpty(),
+ body = c.getString(2).orEmpty(),
+ date = c.getLong(3),
+ outgoing = type != Telephony.Sms.MESSAGE_TYPE_INBOX,
+ status = sentStatus(type),
+ parts = emptyList(),
+ ),
+ )
+ }
+ }
+ }.orEmpty()
+ }
+
+ private fun sentStatus(type: Int): String? = when (type) {
+ Telephony.Sms.MESSAGE_TYPE_SENT -> "sent"
+ Telephony.Sms.MESSAGE_TYPE_OUTBOX, Telephony.Sms.MESSAGE_TYPE_QUEUED -> "pending"
+ Telephony.Sms.MESSAGE_TYPE_FAILED -> "failed"
+ else -> null
+ }
+
+ private fun mms(thread: Long, before: Long?, limit: Int): List<SmsMessage> {
+ val columns = arrayOf(Telephony.Mms._ID, Telephony.Mms.DATE, Telephony.Mms.MESSAGE_BOX)
+ // MMS dates are in seconds.
+ val (selection, args) = page(Telephony.Mms.THREAD_ID, Telephony.Mms.DATE, thread, before?.div(1000))
+ return resolver.query(Telephony.Mms.CONTENT_URI, columns, selection, args, "${Telephony.Mms.DATE} DESC")?.use { c ->
+ buildList {
+ while (size < limit && c.moveToNext()) {
+ val id = c.getLong(0)
+ val box = c.getInt(2)
+ val outgoing = box != Telephony.Mms.MESSAGE_BOX_INBOX
+ val (body, parts) = mmsParts(id)
+ add(
+ SmsMessage(
+ id = "mms:$id",
+ thread = thread.toString(),
+ address = mmsAddress(id, outgoing),
+ body = body,
+ date = c.getLong(1) * 1000,
+ outgoing = outgoing,
+ status = when (box) {
+ Telephony.Mms.MESSAGE_BOX_SENT -> "sent"
+ Telephony.Mms.MESSAGE_BOX_OUTBOX -> "pending"
+ Telephony.Mms.MESSAGE_BOX_FAILED -> "failed"
+ else -> null
+ },
+ parts = parts,
+ ),
+ )
+ }
+ }
+ }.orEmpty()
+ }
+
+ /** Selection for a thread's messages, before a date when paging back. */
+ private fun page(threadColumn: String, dateColumn: String, thread: Long, before: Long?): Pair<String, Array<String>> =
+ if (before == null) {
+ "$threadColumn = ?" to arrayOf(thread.toString())
+ } else {
+ "$threadColumn = ? AND $dateColumn < ?" to arrayOf(thread.toString(), before.toString())
+ }
+
+ /** An MMS's text, and its pictures (and other attachments). */
+ private fun mmsParts(message: Long): Pair<String, List<SmsPart>> {
+ val text = StringBuilder()
+ val parts = mutableListOf<SmsPart>()
+ resolver.query(
+ Uri.parse("content://mms/part"),
+ arrayOf("_id", "ct", "text"),
+ "mid = ?",
+ arrayOf(message.toString()),
+ null,
+ )?.use { c ->
+ while (c.moveToNext()) {
+ val mime = c.getString(1).orEmpty()
+ when {
+ mime == "text/plain" -> c.getString(2)?.let { if (text.isNotEmpty()) text.append('\n'); text.append(it) }
+ mime == "application/smil" -> {}
+ else -> parts += SmsPart(id = "mms-part:${c.getLong(0)}", mime = mime, size = 0u)
+ }
+ }
+ }
+ return text.toString() to parts
+ }
+
+ /** Who sent an MMS (received), or its first recipient (sent). */
+ private fun mmsAddress(message: Long, outgoing: Boolean): String {
+ val type = if (outgoing) PDU_TO else PDU_FROM
+ return resolver.query(
+ Uri.parse("content://mms/$message/addr"),
+ arrayOf("address"),
+ "type = ?",
+ arrayOf(type.toString()),
+ null,
+ )?.use { if (it.moveToFirst()) it.getString(0) else null }.orEmpty()
+ }
+
+ fun part(id: String): SmsPartData? = guarded(null) {
+ val partId = id.removePrefix("mms-part:").takeIf { id.startsWith("mms-part:") }?.toLongOrNull() ?: return@guarded null
+ val uri = Uri.parse("content://mms/part/$partId")
+ val mime = resolver.query(uri, arrayOf("ct"), null, null, null)?.use { if (it.moveToFirst()) it.getString(0) else null }
+ ?: return@guarded null
+ val data = resolver.openInputStream(uri)?.use { input ->
+ val out = ByteArrayOutputStream()
+ val buffer = ByteArray(64 * 1024)
+ while (true) {
+ val n = input.read(buffer)
+ if (n < 0) break
+ out.write(buffer, 0, n)
+ if (out.size() > MAX_PART_BYTES) return@guarded null
+ }
+ out.toByteArray()
+ } ?: return@guarded null
+ SmsPartData(mime, data)
+ }
+
+ // ---- Sending ----
+
+ /** Sends a text to each recipient; Android keeps it in Sent. */
+ fun send(to: List<String>, body: String): Boolean = guarded(false) {
+ if (!granted(context, Manifest.permission.SEND_SMS)) return@guarded false
+ val manager = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
+ context.getSystemService(SmsManager::class.java)
+ } else {
+ @Suppress("DEPRECATION")
+ SmsManager.getDefault()
+ }
+ val parts = manager.divideMessage(body)
+ for (address in to) {
+ manager.sendMultipartTextMessage(address.trim(), null, parts, null, null)
+ }
+ true
+ }
+
+ private inline fun <T> guarded(fallback: T, block: () -> T): T = try {
+ block()
+ } catch (e: Exception) {
+ Log.w(TAG, "can't read or send messages", e)
+ fallback
+ }
+
+ /** Contact names and photos, looked up once per number. */
+ private inner class Contacts {
+ private val allowed = granted(context, Manifest.permission.READ_CONTACTS)
+ private val found = HashMap<String, Pair<String?, String?>>()
+
+ private fun lookup(number: String): Pair<String?, String?> = found.getOrPut(number) {
+ if (!allowed) return@getOrPut null to null
+ val uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number))
+ runCatching {
+ resolver.query(
+ uri,
+ arrayOf(ContactsContract.PhoneLookup.DISPLAY_NAME, ContactsContract.PhoneLookup.PHOTO_THUMBNAIL_URI),
+ null,
+ null,
+ null,
+ )?.use { c: Cursor -> if (c.moveToFirst()) c.getString(0) to c.getString(1) else null }
+ }.getOrNull() ?: (null to null)
+ }
+
+ fun name(number: String): String? = lookup(number).first
+
+ fun photo(number: String): ByteArray? {
+ val uri = lookup(number).second?.let(Uri::parse) ?: return null
+ return runCatching {
+ val bitmap = resolver.openInputStream(uri)?.use { BitmapFactory.decodeStream(it) } ?: return null
+ try {
+ generateSequence(85) { it - 15 }.takeWhile { it >= 40 }
+ .map { q -> ByteArrayOutputStream().also { bitmap.compress(Bitmap.CompressFormat.JPEG, q, it) }.toByteArray() }
+ .firstOrNull { it.size <= MAX_PHOTO_BYTES }
+ } finally {
+ bitmap.recycle()
+ }
+ }.getOrNull()
+ }
+ }
+
+ companion object {
+ private const val TAG = "PhoneSms"
+ private const val SETTLE_MS = 1000L
+ private const val MAX_PART_BYTES = 900 * 1024
+ private const val MAX_PHOTO_BYTES = 16 * 1024
+ /** What a conversation whose latest message is a picture says. */
+ private const val PICTURE_SNIPPET = "Picture"
+ // MMS address types (PduHeaders.FROM and TO).
+ private const val PDU_FROM = 137
+ private const val PDU_TO = 151
+
+ val permissions: Array<String> = arrayOf(
+ Manifest.permission.READ_SMS,
+ Manifest.permission.SEND_SMS,
+ Manifest.permission.READ_CONTACTS,
+ )
+
+ private fun granted(context: Context, permission: String) =
+ ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED
+
+ fun canRead(context: Context) = granted(context, Manifest.permission.READ_SMS)
+
+ fun canSend(context: Context) = granted(context, Manifest.permission.SEND_SMS)
+
+ fun hasAll(context: Context) = permissions.all { granted(context, it) }
+ }
+}
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/ui/home/HomeScreen.kt b/android/app/src/main/kotlin/app/nectarlink/android/ui/home/HomeScreen.kt
index 76fc6f8..c456d1f 100644
--- a/android/app/src/main/kotlin/app/nectarlink/android/ui/home/HomeScreen.kt
+++ b/android/app/src/main/kotlin/app/nectarlink/android/ui/home/HomeScreen.kt
@@ -53,6 +53,7 @@ import app.nectarlink.android.core.Device
import app.nectarlink.android.files.transferTitle
import app.nectarlink.android.calls.PhoneCalls
import app.nectarlink.android.photos.RecentPhotos
+import app.nectarlink.android.sms.PhoneSms
import app.nectarlink.android.core.isFinished
import app.nectarlink.core.Transfer
import app.nectarlink.core.TransferDirection
@@ -138,6 +139,17 @@ fun HomeScreen(
) { context.startActivity(NotificationListener.settingsIntent(context)) }
}
}
+ if (state.devices.isNotEmpty() && !state.smsAccess) {
+ item {
+ val askSms = rememberLauncherForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) {
+ onAccessChanged()
+ }
+ SetupCard(
+ stringResource(R.string.sms_title),
+ stringResource(R.string.sms_off),
+ ) { askSms.launch(PhoneSms.permissions) }
+ }
+ }
if (state.devices.isNotEmpty() && !state.callAccess) {
item {
val askCalls = rememberLauncherForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) {
diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml
index a77ac17..b1edb10 100644
--- a/android/app/src/main/res/values/strings.xml
+++ b/android/app/src/main/res/values/strings.xml
@@ -67,6 +67,8 @@
<string name="media_previous">Previous</string>
<string name="action_send_files">Send files</string>
<string name="action_send_folder">Send a folder</string>
+ <string name="sms_title">Text from your PC</string>
+ <string name="sms_off">Read your conversations and send texts from your PC. Nectarlink needs access to your messages and contacts for that.</string>
<string name="calls_title">Show calls on your PC</string>
<string name="calls_off">See who’s calling on your PC, and answer or decline from there. The call itself stays on your phone. Nectarlink needs access to calls and contacts for that.</string>
<string name="photos_title">Show new photos on your PC</string>
diff --git a/core/nectarlink-cli/src/main.rs b/core/nectarlink-cli/src/main.rs
index 3a1901c..28cd663 100644
--- a/core/nectarlink-cli/src/main.rs
+++ b/core/nectarlink-cli/src/main.rs
@@ -164,6 +164,15 @@ enum Command {
/// Show new photos from paired phones as this PC would, and fetch each
/// one; stays online until Ctrl+C.
Photos,
+ /// Act as a phone with a few sample conversations (use with --as-phone),
+ /// so a PC can read them and text through this client; stays online.
+ Texts,
+ /// A paired phone's text messages: list conversations, show one, or send.
+ Sms {
+ device: String,
+ #[command(subcommand)]
+ action: SmsArg,
+ },
/// Show calls on paired phones as this PC would; with --auto, answer,
/// decline or silence each ringing call. Stays online until Ctrl+C.
Calls {
@@ -250,6 +259,23 @@ impl From<MediaCommandArg> for MediaAction {
static MEDIA_COMMANDS: std::sync::OnceLock<tokio::sync::mpsc::UnboundedSender<(MediaAction, Option<u64>)>> =
std::sync::OnceLock::new();
+#[derive(Debug, Subcommand)]
+enum SmsArg {
+ /// The latest conversations.
+ Threads {
+ #[arg(long, default_value_t = 20)]
+ limit: u32,
+ },
+ /// A conversation's latest messages.
+ Show {
+ thread: String,
+ #[arg(long, default_value_t = 20)]
+ limit: u32,
+ },
+ /// Send a text.
+ Send { to: String, body: String },
+}
+
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
enum CallArg {
Answer,
@@ -263,6 +289,38 @@ enum OnOff {
Off,
}
+/// A sample text for `texts`: (thread, number, name, incoming, body, Unix ms).
+type SampleText = (u32, String, String, bool, String, i64);
+static TEXTS: std::sync::Mutex<Vec<SampleText>> = std::sync::Mutex::new(Vec::new());
+/// Set by `texts`, to tell PCs when the samples changed.
+static TEXTS_NODE: std::sync::OnceLock<Node> = std::sync::OnceLock::new();
+
+fn sample_texts() {
+ let now = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map_or(0, |d| d.as_millis() as i64);
+ let min = 60_000;
+ let samples = [
+ (1, "+15550100", "Sam Rivera", true, "Are we still on for dinner tonight?", now - 50 * min),
+ (1, "+15550100", "Sam Rivera", false, "Yes! 7:30 at the usual place", now - 48 * min),
+ (1, "+15550100", "Sam Rivera", true, "Perfect. I'll book a table 🍜", now - 47 * min),
+ (
+ 2,
+ "+15550123",
+ "",
+ true,
+ "Your parcel will arrive tomorrow between 9:00 and 13:00.",
+ now - 26 * 60 * min,
+ ),
+ (3, "+15550188", "Alex", false, "Can you send me the photos from Saturday?", now - 3 * 24 * 60 * min),
+ (3, "+15550188", "Alex", true, "Sure, uploading them now", now - 3 * 24 * 60 * min + 5 * min),
+ ];
+ *TEXTS.lock().unwrap() = samples
+ .into_iter()
+ .map(|(t, n, name, incoming, body, date)| (t, n.into(), name.into(), incoming, body.into(), date))
+ .collect();
+}
+
/// The picture `photo` announced, for PCs that ask for it.
static PHOTO: std::sync::OnceLock<PathBuf> = std::sync::OnceLock::new();
const PHOTO_ID: &str = "cli-photo";
@@ -272,6 +330,72 @@ const PHOTO_ID: &str = "cli-photo";
struct TerminalPlatform;
impl Platform for TerminalPlatform {
+ fn sms_threads(&self, limit: u32) -> std::result::Result<Vec<nectarlink_core::SmsThread>, String> {
+ let texts = TEXTS.lock().unwrap();
+ let mut threads: Vec<nectarlink_core::SmsThread> = Vec::new();
+ for (thread, number, name, incoming, body, date) in texts.iter() {
+ match threads.iter_mut().find(|t| t.id == thread.to_string()) {
+ Some(t) if *date > t.date => {
+ t.date = *date;
+ t.snippet = body.clone();
+ t.unread = u32::from(*incoming);
+ }
+ Some(_) => {}
+ None => threads.push(nectarlink_core::SmsThread {
+ id: thread.to_string(),
+ addresses: vec![number.clone()],
+ names: vec![name.clone()],
+ snippet: body.clone(),
+ date: *date,
+ unread: u32::from(*incoming),
+ photo: None,
+ }),
+ }
+ }
+ threads.sort_by_key(|t| std::cmp::Reverse(t.date));
+ threads.truncate(limit as usize);
+ Ok(threads)
+ }
+ fn sms_messages(
+ &self,
+ thread: &str,
+ before: Option<i64>,
+ limit: u32,
+ ) -> std::result::Result<Vec<nectarlink_core::SmsMessage>, String> {
+ let texts = TEXTS.lock().unwrap();
+ let mut messages: Vec<nectarlink_core::SmsMessage> = texts
+ .iter()
+ .enumerate()
+ .filter(|(_, (t, .., date))| t.to_string() == thread && before.is_none_or(|b| *date < b))
+ .map(|(i, (t, number, _, incoming, body, date))| nectarlink_core::SmsMessage {
+ id: format!("sms:{i}"),
+ thread: t.to_string(),
+ address: number.clone(),
+ body: body.clone(),
+ date: *date,
+ outgoing: !incoming,
+ status: (!incoming).then(|| "sent".into()),
+ parts: Vec::new(),
+ })
+ .collect();
+ messages.sort_by_key(|m| std::cmp::Reverse(m.date));
+ messages.truncate(limit as usize);
+ Ok(messages)
+ }
+ fn sms_send(&self, to: &[String], body: &str) -> std::result::Result<(), String> {
+ println!("A PC sent a text to {}: {body}", to.join(", "));
+ let now = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map_or(0, |d| d.as_millis() as i64);
+ let mut texts = TEXTS.lock().unwrap();
+ let thread = texts.iter().find(|(_, n, ..)| *n == to[0]).map(|(t, ..)| *t);
+ let thread = thread.unwrap_or_else(|| texts.iter().map(|(t, ..)| *t).max().unwrap_or(0) + 1);
+ texts.push((thread, to[0].clone(), String::new(), false, body.to_owned(), now));
+ if let Some(node) = TEXTS_NODE.get().cloned() {
+ tokio::runtime::Handle::current().spawn(async move { node.sms_changed(None).await });
+ }
+ Ok(())
+ }
fn open_photo(&self, id: &str) -> std::result::Result<nectarlink_core::OutgoingFile, String> {
let path = PHOTO.get().filter(|_| id == PHOTO_ID).ok_or("no such photo")?;
println!("A PC asked for the photo; sending it.");
@@ -526,6 +650,67 @@ async fn run(cli: &Cli, node: &Node) -> Result<()> {
node.update_power(node_power(cli), offers).await;
watch(node, true).await?;
}
+ Command::Texts => {
+ if !cli.as_phone {
+ bail!("texts are on phones: add --as-phone");
+ }
+ sample_texts();
+ let _ = TEXTS_NODE.set(node.clone());
+ let mut offers = cli.offers.clone();
+ offers.extend([nectarlink_core::SMS_READ.to_owned(), nectarlink_core::SMS_SEND.to_owned()]);
+ node.update_power(node_power(cli), offers).await;
+ println!("Sharing sample conversations with paired PCs.");
+ watch(node, false).await?;
+ }
+ Command::Sms { device, action } => {
+ let mut offers = cli.offers.clone();
+ offers.push(nectarlink_core::SMS_SHOW.into());
+ node.update_power(node_power(cli), offers).await;
+ let id = resolve(node, device)?;
+ wait_until_online(node, id).await?;
+ match action {
+ SmsArg::Threads { limit } => {
+ for t in node.sms_threads(id, *limit).await.context("can't list conversations")? {
+ let who: Vec<String> = t
+ .addresses
+ .iter()
+ .zip(t.names.iter().map(Some).chain(std::iter::repeat(None)))
+ .map(|(a, n)| match n.filter(|n| !n.is_empty()) {
+ Some(n) => format!("{n} ({a})"),
+ None => a.clone(),
+ })
+ .collect();
+ println!(
+ "[{}] {}{}: {}{}",
+ t.id,
+ who.join(", "),
+ if t.unread > 0 { format!(" · {} unread", t.unread) } else { String::new() },
+ t.snippet,
+ if t.photo.is_some() { " (photo)" } else { "" }
+ );
+ }
+ }
+ SmsArg::Show { thread, limit } => {
+ let mut messages =
+ node.sms_messages(id, thread.clone(), None, *limit).await.context("can't read it")?;
+ messages.reverse();
+ for m in messages {
+ println!(
+ "{} {}: {}{}{}",
+ if m.outgoing { "→" } else { "←" },
+ m.address,
+ m.body,
+ m.parts.iter().map(|p| format!(" [{} {}]", p.mime, p.id)).collect::<String>(),
+ m.status.map(|s| format!(" ({s})")).unwrap_or_default()
+ );
+ }
+ }
+ SmsArg::Send { to, body } => {
+ node.sms_send(id, vec![to.clone()], body.clone()).await.context("not sent")?;
+ println!("Sent.");
+ }
+ }
+ }
Command::Calls { auto } => {
let mut offers = cli.offers.clone();
offers.push(nectarlink_core::CALLS_SHOW.into());
diff --git a/core/nectarlink-core/src/config.rs b/core/nectarlink-core/src/config.rs
index 9cbefd1..364cb0c 100644
--- a/core/nectarlink-core/src/config.rs
+++ b/core/nectarlink-core/src/config.rs
@@ -123,6 +123,32 @@ pub trait Platform: Send + Sync + 'static {
Err("this device doesn't share photos".into())
}
+ /// This phone's latest conversations, newest first (a PC asked).
+ fn sms_threads(&self, _limit: u32) -> Result<Vec<crate::SmsThread>, String> {
+ Err("this device has no messages".into())
+ }
+
+ /// A conversation's messages before `before` (Unix ms; the latest when
+ /// `None`), newest first.
+ fn sms_messages(
+ &self,
+ _thread: &str,
+ _before: Option<i64>,
+ _limit: u32,
+ ) -> Result<Vec<crate::SmsMessage>, String> {
+ Err("this device has no messages".into())
+ }
+
+ /// Send a text (checked: 1–20 recipients, not empty).
+ fn sms_send(&self, _to: &[String], _body: &str) -> Result<(), String> {
+ Err("this device doesn't send texts".into())
+ }
+
+ /// A picture in a message: its type and bytes.
+ fn sms_part(&self, _id: &str) -> Result<(String, Vec<u8>), String> {
+ Err("this device has no messages".into())
+ }
+
/// Answer, decline or silence this phone's call `id` (a PC asked; the
/// core checked it's the call in progress). `Err` holds a reason for logs.
fn call_command(&self, _id: &str, _command: crate::CallCommand) -> Result<(), String> {
diff --git a/core/nectarlink-core/src/events.rs b/core/nectarlink-core/src/events.rs
index 0425b7d..15a1c9f 100644
--- a/core/nectarlink-core/src/events.rs
+++ b/core/nectarlink-core/src/events.rs
@@ -139,4 +139,9 @@ pub enum NodeEvent {
device: DeviceId,
call: crate::CallState,
},
+ /// A phone's messages changed: in `thread`, or anywhere when `None`.
+ SmsChanged {
+ device: DeviceId,
+ thread: Option<String>,
+ },
}
diff --git a/core/nectarlink-core/src/lib.rs b/core/nectarlink-core/src/lib.rs
index 71382a0..12a8a52 100644
--- a/core/nectarlink-core/src/lib.rs
+++ b/core/nectarlink-core/src/lib.rs
@@ -20,6 +20,7 @@ mod notifications;
mod pairing;
mod photos;
mod session;
+mod sms;
mod store;
mod transfer;
@@ -40,9 +41,10 @@ pub use nectarlink_protocol::{
DeviceId,
messages::{
Battery, CLIP_MAX_BYTES, CallState, DeviceInfo, DeviceKind, MediaPlayer, Notification,
- NotificationAction, PhotoNew as Photo, PowerLevel,
+ NotificationAction, PhotoNew as Photo, PowerLevel, SmsMessage, SmsPart, SmsThread,
calls::{CONTROL as CALLS_CONTROL, SHOW as CALLS_SHOW, STATE as CALLS_STATE},
photos::{MAX_THUMB_BYTES as PHOTO_MAX_THUMB_BYTES, READ as PHOTOS_READ, SHOW as PHOTOS_SHOW},
+ sms::{READ as SMS_READ, SEND as SMS_SEND, SHOW as SMS_SHOW},
},
pairing::PairingUri,
};
diff --git a/core/nectarlink-core/src/node.rs b/core/nectarlink-core/src/node.rs
index a96497a..7d11aff 100644
--- a/core/nectarlink-core/src/node.rs
+++ b/core/nectarlink-core/src/node.rs
@@ -921,6 +921,45 @@ impl Node {
crate::actions::open_link(&self.shared, &session, url).await
}
+ // ---- Messages (docs/protocol/sms.md) ----
+
+ /// This phone's messages changed (in `thread`, or anywhere): connected
+ /// PCs that show them catch up.
+ pub async fn sms_changed(&self, thread: Option<String>) {
+ self.shared.sms_changed(thread).await;
+ }
+
+ /// A paired phone's latest conversations, newest first.
+ pub async fn sms_threads(&self, peer: DeviceId, limit: u32) -> Result<Vec<crate::SmsThread>> {
+ let session = self.connected(&peer)?;
+ crate::sms::threads(&self.shared, &session, limit).await
+ }
+
+ /// A conversation's messages before `before` (Unix ms; the latest when
+ /// `None`), newest first.
+ pub async fn sms_messages(
+ &self,
+ peer: DeviceId,
+ thread: String,
+ before: Option<i64>,
+ limit: u32,
+ ) -> Result<Vec<crate::SmsMessage>> {
+ let session = self.connected(&peer)?;
+ crate::sms::messages(&self.shared, &session, thread, before, limit).await
+ }
+
+ /// Sends a text through a paired phone.
+ pub async fn sms_send(&self, peer: DeviceId, to: Vec<String>, body: String) -> Result<()> {
+ let session = self.connected(&peer)?;
+ crate::sms::send(&self.shared, &session, to, body).await
+ }
+
+ /// A picture in a message: its type and bytes.
+ pub async fn sms_part(&self, peer: DeviceId, id: String) -> Result<(String, Vec<u8>)> {
+ let session = self.connected(&peer)?;
+ crate::sms::part(&self.shared, &session, id).await
+ }
+
// ---- Calls (docs/protocol/calls.md) ----
/// A call on this phone rang, was answered or ended; sent to every
diff --git a/core/nectarlink-core/src/session.rs b/core/nectarlink-core/src/session.rs
index 65a6062..71eeaf8 100644
--- a/core/nectarlink-core/src/session.rs
+++ b/core/nectarlink-core/src/session.rs
@@ -352,6 +352,7 @@ async fn handle(shared: &Arc<Shared>, session: &Arc<Session>, env: Envelope) ->
t if t.starts_with("clip.") && crate::clipboard::handle(shared, session, &env).await? => {}
t if t.starts_with("photos.") && crate::photos::handle(shared, session, &env).await? => {}
t if t.starts_with("call.") && crate::calls::handle(shared, session, &env).await? => {}
+ t if t.starts_with("sms.") && crate::sms::handle(shared, session, &env).await? => {}
other => {
if env.id.is_some() {
let reply = Envelope::error(ErrorCode::Unsupported, format!("unknown message type {other}"));
diff --git a/core/nectarlink-core/src/sms.rs b/core/nectarlink-core/src/sms.rs
new file mode 100644
index 0000000..ea2035c
--- /dev/null
+++ b/core/nectarlink-core/src/sms.rs
@@ -0,0 +1,226 @@
+// SPDX-License-Identifier: MPL-2.0
+//! Text messages (docs/protocol/sms.md): a PC lists a phone's
+//! conversations and their messages, fetches pictures in them, and sends
+//! texts through the phone; the phone says when something changed.
+
+use std::sync::Arc;
+
+use nectarlink_protocol::{
+ DeviceId, Envelope, ErrorCode, MAX_FRAME_LEN,
+ messages::{
+ SmsChanged, SmsMessage, SmsMessages, SmsMessagesGet, SmsPartData, SmsPartGet, SmsSend, SmsThread,
+ SmsThreads, SmsThreadsGet, sms, types,
+ },
+};
+
+use crate::{Error, Result, events::NodeEvent, node::Shared, session::Session};
+
+/// The device toggle that allows messages for a device.
+pub(crate) const TOGGLE: &str = "messages";
+/// Room left in a frame for the envelope around a list.
+const FRAME_MARGIN: usize = 4 * 1024;
+
+impl Shared {
+ fn sms_target(&self, session: &Session) -> bool {
+ self.is_desktop(&session.peer)
+ && self.toggle_on(&session.peer, TOGGLE)
+ && self.store.get_peer(&session.peer).ok().flatten().is_some_and(|p| p.caps.contains(sms::SHOW))
+ }
+
+ pub(crate) async fn sms_changed(&self, thread: Option<String>) {
+ let Ok(env) = Envelope::new(types::SMS_CHANGED, &SmsChanged { thread }) else { return };
+ for session in self.live_sessions().into_iter().filter(|s| self.sms_target(s)) {
+ let _ = session.send(env.clone()).await;
+ }
+ }
+
+ fn offers_locally(&self, capability: &str) -> bool {
+ self.local_capabilities().iter().any(|c| c == capability)
+ }
+}
+
+// ---- A PC asking ----
+
+fn allowed(shared: &Shared, peer: &DeviceId) -> Result<()> {
+ if shared.toggle_on(peer, TOGGLE) { Ok(()) } else { Err(Error::Denied) }
+}
+
+pub(crate) async fn threads(shared: &Shared, session: &Session, limit: u32) -> Result<Vec<SmsThread>> {
+ allowed(shared, &session.peer)?;
+ let env = Envelope::new(types::SMS_THREADS, &SmsThreadsGet { limit: limit.min(sms::MAX_PAGE) })?;
+ let SmsThreads { threads } =
+ session.request(env, crate::session::REQUEST_TIMEOUT).await?.expect_body(types::SMS_THREADS)?;
+ Ok(threads)
+}
+
+pub(crate) async fn messages(
+ shared: &Shared,
+ session: &Session,
+ thread: String,
+ before: Option<i64>,
+ limit: u32,
+) -> Result<Vec<SmsMessage>> {
+ allowed(shared, &session.peer)?;
+ let env = Envelope::new(
+ types::SMS_MESSAGES,
+ &SmsMessagesGet { thread, before, limit: limit.min(sms::MAX_PAGE) },
+ )?;
+ let SmsMessages { messages } =
+ session.request(env, crate::session::REQUEST_TIMEOUT).await?.expect_body(types::SMS_MESSAGES)?;
+ Ok(messages)
+}
+
+pub(crate) async fn send(shared: &Shared, session: &Session, to: Vec<String>, body: String) -> Result<()> {
+ allowed(shared, &session.peer)?;
+ let send = SmsSend { to, body };
+ if !send.is_valid() {
+ return Err(if send.body.len() > sms::MAX_SEND_BYTES {
+ Error::TooLarge
+ } else {
+ Error::Protocol("invalid text".into())
+ });
+ }
+ let env = Envelope::new(types::SMS_SEND, &send)?;
+ session.request(env, crate::session::REQUEST_TIMEOUT).await?.expect(types::OK)?;
+ Ok(())
+}
+
+pub(crate) async fn part(shared: &Shared, session: &Session, id: String) -> Result<(String, Vec<u8>)> {
+ allowed(shared, &session.peer)?;
+ let env = Envelope::new(types::SMS_PART, &SmsPartGet { id })?;
+ let SmsPartData { mime, data } =
+ session.request(env, crate::session::REQUEST_TIMEOUT).await?.expect_body(types::SMS_PART)?;
+ Ok((mime, data))
+}
+
+// ---- The phone answering ----
+
+/// Handles `sms.*`. Returns false for other types.
+pub(crate) async fn handle(shared: &Arc<Shared>, session: &Arc<Session>, env: &Envelope) -> Result<bool> {
+ if env.t == types::SMS_CHANGED {
+ let SmsChanged { thread } = env.body()?;
+ if shared.offers_locally(sms::SHOW) && shared.toggle_on(&session.peer, TOGGLE) {
+ shared.emit(NodeEvent::SmsChanged { device: session.peer, thread });
+ }
+ return Ok(true);
+ }
+ if ![types::SMS_THREADS, types::SMS_MESSAGES, types::SMS_SEND, types::SMS_PART].contains(&env.t.as_str())
+ {
+ return Ok(false);
+ }
+ // Reading the phone's messages takes a moment: not on the session's loop.
+ let (shared, session, env) = (shared.clone(), session.clone(), env.clone());
+ tokio::spawn(async move {
+ let reply = answer(&shared, &session, &env).await.unwrap_or_else(|e| {
+ tracing::debug!(error = %e, "bad messages request");
+ Envelope::error(ErrorCode::BadMessage, "invalid request")
+ });
+ let _ = session.send(reply.reply_to(env.id)).await;
+ });
+ Ok(true)
+}
+
+async fn answer(shared: &Arc<Shared>, session: &Session, env: &Envelope) -> Result<Envelope> {
+ if !shared.toggle_on(&session.peer, TOGGLE) {
+ return Ok(Envelope::error(ErrorCode::Denied, "messages are off for this device"));
+ }
+ let needs = if env.t == types::SMS_SEND { sms::SEND } else { sms::READ };
+ if !shared.offers_locally(needs) {
+ return Ok(Envelope::error(ErrorCode::Unsupported, "this phone doesn't share messages"));
+ }
+ let platform = shared.platform.clone();
+ let blocking = |f: Box<dyn FnOnce() -> std::result::Result<Envelope, String> + Send>| async move {
+ tokio::task::spawn_blocking(f).await.unwrap_or_else(|e| Err(e.to_string()))
+ };
+ let result = match env.t.as_str() {
+ types::SMS_THREADS => {
+ let SmsThreadsGet { limit } = env.body()?;
+ blocking(Box::new(move || {
+ let mut threads = platform.sms_threads(limit.min(sms::MAX_PAGE))?;
+ for t in &mut threads {
+ if t.photo.as_ref().is_some_and(|p| p.len() > sms::MAX_PHOTO_BYTES) {
+ t.photo = None;
+ }
+ }
+ fit(threads, |threads| Envelope::new(types::SMS_THREADS, &SmsThreads { threads }))
+ }))
+ .await
+ }
+ types::SMS_MESSAGES => {
+ let SmsMessagesGet { thread, before, limit } = env.body()?;
+ blocking(Box::new(move || {
+ let messages = platform.sms_messages(&thread, before, limit.min(sms::MAX_PAGE))?;
+ fit(messages, |messages| Envelope::new(types::SMS_MESSAGES, &SmsMessages { messages }))
+ }))
+ .await
+ }
+ types::SMS_SEND => {
+ let send: SmsSend = env.body()?;
+ if !send.is_valid() {
+ return Ok(Envelope::error(ErrorCode::BadMessage, "invalid text"));
+ }
+ blocking(Box::new(move || {
+ platform.sms_send(&send.to, &send.body).map(|()| Envelope::empty(types::OK))
+ }))
+ .await
+ }
+ _ => {
+ let SmsPartGet { id } = env.body()?;
+ blocking(Box::new(move || {
+ let (mime, data) = platform.sms_part(&id)?;
+ if data.len() > sms::MAX_PART_BYTES {
+ return Ok(Envelope::error(ErrorCode::Busy, "too large"));
+ }
+ Envelope::new(types::SMS_PART, &SmsPartData { mime, data }).map_err(|e| e.to_string())
+ }))
+ .await
+ }
+ };
+ Ok(result.unwrap_or_else(|reason| {
+ tracing::warn!(reason, t = env.t, "a messages request failed");
+ Envelope::error(ErrorCode::Internal, "the phone couldn't do it")
+ }))
+}
+
+/// The envelope for as many of `items` (newest first) as fit in a frame.
+fn fit<T: Clone>(
+ mut items: Vec<T>,
+ wrap: impl Fn(Vec<T>) -> std::result::Result<Envelope, nectarlink_protocol::ProtocolError>,
+) -> std::result::Result<Envelope, String> {
+ loop {
+ let env = wrap(items.clone()).map_err(|e| e.to_string())?;
+ if env.to_cbor().len() + FRAME_MARGIN <= MAX_FRAME_LEN || items.is_empty() {
+ return Ok(env);
+ }
+ // Drop the oldest quarter and try again.
+ let keep = items.len() - items.len().div_ceil(4);
+ items.truncate(keep);
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn long_lists_are_cut_to_fit_a_frame() {
+ let message = |i: usize| SmsMessage {
+ id: i.to_string(),
+ thread: "1".into(),
+ address: "+1555".into(),
+ body: "x".repeat(20_000),
+ date: i as i64,
+ outgoing: false,
+ status: None,
+ parts: Vec::new(),
+ };
+ let env = fit((0..100).map(message).collect(), |messages| {
+ Envelope::new(types::SMS_MESSAGES, &SmsMessages { messages })
+ })
+ .unwrap();
+ assert!(env.to_cbor().len() <= MAX_FRAME_LEN);
+ let SmsMessages { messages } = env.body().unwrap();
+ assert!(messages.len() >= 30 && messages.len() < 100, "{}", messages.len());
+ assert_eq!(messages[0].id, "0", "the newest stay");
+ }
+}
diff --git a/core/nectarlink-core/tests/two_devices.rs b/core/nectarlink-core/tests/two_devices.rs
index ba0ae75..122b97f 100644
--- a/core/nectarlink-core/tests/two_devices.rs
+++ b/core/nectarlink-core/tests/two_devices.rs
@@ -31,6 +31,7 @@ struct RecordingPlatform {
power: Mutex<Vec<PowerAction>>,
links: Mutex<Vec<String>>,
calls: Mutex<Vec<(String, nectarlink_core::CallCommand)>>,
+ texts: Mutex<Vec<(Vec<String>, String)>>,
/// Photos `open_photo` finds, by ID.
photos: Mutex<std::collections::HashMap<String, std::path::PathBuf>>,
}
@@ -74,6 +75,44 @@ impl Platform for RecordingPlatform {
self.links.lock().unwrap().push(url.to_owned());
Ok(())
}
+ fn sms_threads(&self, limit: u32) -> Result<Vec<nectarlink_core::SmsThread>, String> {
+ let thread = |i: u32| nectarlink_core::SmsThread {
+ id: i.to_string(),
+ addresses: vec![format!("+1555010{i}")],
+ names: vec![],
+ snippet: format!("text {i}"),
+ date: 1_790_000_000_000 - i64::from(i),
+ unread: i % 2,
+ photo: None,
+ };
+ Ok((0..5).map(thread).take(limit as usize).collect())
+ }
+ fn sms_messages(
+ &self,
+ thread: &str,
+ before: Option<i64>,
+ limit: u32,
+ ) -> Result<Vec<nectarlink_core::SmsMessage>, String> {
+ let message = |date: i64| nectarlink_core::SmsMessage {
+ id: date.to_string(),
+ thread: thread.to_owned(),
+ address: "+15550100".into(),
+ body: format!("at {date}"),
+ date,
+ outgoing: date % 2 == 0,
+ status: None,
+ parts: vec![nectarlink_core::SmsPart { id: "p1".into(), mime: "image/jpeg".into(), size: 3 }],
+ };
+ let newest = before.unwrap_or(100);
+ Ok((0..newest).rev().take(limit as usize).map(message).collect())
+ }
+ fn sms_send(&self, to: &[String], body: &str) -> Result<(), String> {
+ self.texts.lock().unwrap().push((to.to_vec(), body.to_owned()));
+ Ok(())
+ }
+ fn sms_part(&self, id: &str) -> Result<(String, Vec<u8>), String> {
+ if id == "p1" { Ok(("image/jpeg".into(), vec![1, 2, 3])) } else { Err("gone".into()) }
+ }
fn call_command(&self, id: &str, command: nectarlink_core::CallCommand) -> Result<(), String> {
self.calls.lock().unwrap().push((id.to_owned(), command));
Ok(())
@@ -948,6 +987,48 @@ async fn folders_arrive_with_their_layout() {
);
}
+#[tokio::test(flavor = "multi_thread")]
+async fn the_pc_reads_and_sends_texts_through_the_phone() {
+ let mut pc = device_with("Desktop", DeviceKind::Desktop, &[nectarlink_core::SMS_SHOW]).await;
+ let mut phone =
+ device_with("Pixel", DeviceKind::Phone, &[nectarlink_core::SMS_READ, nectarlink_core::SMS_SEND])
+ .await;
+ pair_qr(&mut pc, &mut phone).await;
+ let (pc_id, phone_id) = (pc.node.device_id(), phone.node.device_id());
+
+ let threads = with_timeout("threads", pc.node.sms_threads(phone_id, 3)).await.unwrap();
+ assert_eq!(threads.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(), ["0", "1", "2"]);
+
+ // Paging back through a conversation.
+ let latest = pc.node.sms_messages(phone_id, "1".into(), None, 10).await.unwrap();
+ assert_eq!((latest[0].date, latest.len()), (99, 10));
+ let older = pc.node.sms_messages(phone_id, "1".into(), Some(latest[9].date), 10).await.unwrap();
+ assert_eq!(older[0].date, 89);
+
+ let (mime, data) = pc.node.sms_part(phone_id, "p1".into()).await.unwrap();
+ assert_eq!((mime.as_str(), data.as_slice()), ("image/jpeg", [1u8, 2, 3].as_slice()));
+
+ pc.node.sms_send(phone_id, vec!["+15550100".into()], "On my way".into()).await.unwrap();
+ assert_eq!(
+ *phone.platform.texts.lock().unwrap(),
+ [(vec!["+15550100".to_owned()], "On my way".to_owned())]
+ );
+ assert!(matches!(pc.node.sms_send(phone_id, vec![], "x".into()).await, Err(Error::Protocol(_))));
+
+ // The phone says what changed.
+ phone.node.sms_changed(Some("1".into())).await;
+ let changed = wait_for(&mut pc, "a change", |e| match e {
+ NodeEvent::SmsChanged { device, thread } if *device == phone_id => Some(thread.clone()),
+ _ => None,
+ })
+ .await;
+ assert_eq!(changed.as_deref(), Some("1"));
+
+ // The phone's user turned messages off for this PC.
+ phone.node.set_device_toggle(pc_id, "messages", false).unwrap();
+ assert!(matches!(pc.node.sms_threads(phone_id, 3).await, Err(Error::Denied)));
+}
+
#[tokio::test(flavor = "multi_thread")]
async fn calls_show_on_the_pc_which_can_answer_them() {
use nectarlink_core::{CallCommand, CallState};
@@ -969,16 +1050,20 @@ async fn calls_show_on_the_pc_which_can_answer_them() {
photo: Some(vec![0xff, 0xd8]),
missed: false,
};
- async fn next_call(pc: &mut TestDevice, phone_id: nectarlink_core::DeviceId) -> CallState {
- wait_for(pc, "a call", |e| match e {
- NodeEvent::Call { device, call } if *device == phone_id => Some(call.clone()),
+ // The call in `state` (a PC that just connected may hear the earlier
+ // one again).
+ async fn next_call(pc: &mut TestDevice, phone_id: nectarlink_core::DeviceId, state: &str) -> CallState {
+ wait_for(pc, state, |e| match e {
+ NodeEvent::Call { device, call } if *device == phone_id && call.state == state => {
+ Some(call.clone())
+ }
_ => None,
})
.await
}
phone.node.call_changed(ringing.clone()).await.unwrap();
- assert_eq!(next_call(&mut pc, phone_id).await, ringing);
+ assert_eq!(next_call(&mut pc, phone_id, "ringing").await, ringing);
with_timeout("answer", pc.node.call_command(phone_id, "c1".into(), CallCommand::Answer)).await.unwrap();
assert_eq!(*phone.platform.calls.lock().unwrap(), [("c1".to_owned(), CallCommand::Answer)]);
// Only the call in progress.
@@ -989,7 +1074,7 @@ async fn calls_show_on_the_pc_which_can_answer_them() {
let active = CallState { state: "active".into(), photo: None, ..ringing.clone() };
phone.node.call_changed(active.clone()).await.unwrap();
- assert_eq!(next_call(&mut pc, phone_id).await.state, "active");
+ next_call(&mut pc, phone_id, "active").await;
// An answered call doesn't ring anymore, but can be hung up.
assert!(matches!(
pc.node.call_command(phone_id, "c1".into(), CallCommand::Silence).await,
@@ -999,7 +1084,7 @@ async fn calls_show_on_the_pc_which_can_answer_them() {
let ended = CallState { state: "ended".into(), ..active };
phone.node.call_changed(ended).await.unwrap();
- assert_eq!(next_call(&mut pc, phone_id).await.state, "ended");
+ next_call(&mut pc, phone_id, "ended").await;
assert!(matches!(
pc.node.call_command(phone_id, "c1".into(), CallCommand::Decline).await,
Err(Error::NotFound)
diff --git a/core/nectarlink-ffi/src/lib.rs b/core/nectarlink-ffi/src/lib.rs
index 808be9c..2c9e6c1 100644
--- a/core/nectarlink-ffi/src/lib.rs
+++ b/core/nectarlink-ffi/src/lib.rs
@@ -434,7 +434,72 @@ pub enum Event {
id: String,
call_id: String,
},
+ /// A paired phone's messages changed (PCs only).
+ SmsChanged {
+ id: String,
+ thread: Option<String>,
+ },
+}
+
+/// A conversation (docs/protocol/sms.md).
+#[derive(Clone, PartialEq, Eq, uniffi::Record)]
+pub struct SmsThread {
+ pub id: String,
+ /// The other people's numbers (more than one: a group).
+ pub addresses: Vec<String>,
+ /// Their contact names, in the same order ("" when not a contact).
+ pub names: Vec<String>,
+ /// The latest message's text, or a description like "Photo".
+ pub snippet: String,
+ /// Unix milliseconds.
+ pub date: i64,
+ pub unread: u32,
+ /// The contact's photo (one-person conversations): a JPEG of at most 16 KB.
+ pub photo: Option<Vec<u8>>,
+}
+
+/// A message in a conversation.
+#[derive(Clone, PartialEq, Eq, uniffi::Record)]
+pub struct SmsMessage {
+ pub id: String,
+ pub thread: String,
+ /// Who sent it (received), or the recipient (sent).
+ pub address: String,
+ pub body: String,
+ /// Unix milliseconds.
+ pub date: i64,
+ pub outgoing: bool,
+ /// Sent messages: "sent", "pending" or "failed".
+ pub status: Option<String>,
+ /// Pictures and other attachments, fetched with `sms_part`.
+ pub parts: Vec<SmsPart>,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq, uniffi::Record)]
+pub struct SmsPart {
+ pub id: String,
+ pub mime: String,
+ pub size: u64,
+}
+
+/// An attachment's bytes.
+#[derive(Clone, PartialEq, Eq, uniffi::Record)]
+pub struct SmsPartData {
+ pub mime: String,
+ pub data: Vec<u8>,
+}
+
+macro_rules! private_debug {
+ ($($t:ty),*) => {$(
+ /// Never prints numbers, names or text (protocol v0 §11).
+ impl std::fmt::Debug for $t {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct(stringify!($t)).finish_non_exhaustive()
+ }
+ }
+ )*};
}
+private_debug!(SmsThread, SmsMessage, SmsPartData);
/// A call on this phone (docs/protocol/calls.md).
#[derive(Clone, PartialEq, Eq, uniffi::Record)]
@@ -868,6 +933,7 @@ impl From<NodeEvent> for Event {
NodeEvent::Call { device, call } => {
Event::CallChanged { id: device.to_string(), call_id: call.id }
}
+ NodeEvent::SmsChanged { device, thread } => Event::SmsChanged { id: device.to_string(), thread },
}
}
}
@@ -977,6 +1043,16 @@ pub trait Platform: Send + Sync {
/// A PC asked to answer, decline or silence call `id` (the call in
/// progress). False if the phone couldn't.
fn call_command(&self, id: String, command: CallCommand) -> bool;
+ /// A PC asked for the latest conversations, newest first.
+ fn sms_threads(&self, limit: u32) -> Vec<SmsThread>;
+ /// A PC asked for a conversation's messages before `before` (Unix ms;
+ /// the latest when null), newest first.
+ fn sms_messages(&self, thread: String, before: Option<i64>, limit: u32) -> Vec<SmsMessage>;
+ /// A PC asked to send a text (checked: 1–20 recipients, not empty).
+ /// False if it couldn't be sent.
+ fn sms_send(&self, to: Vec<String>, body: String) -> bool;
+ /// A PC asked for a message's attachment; null when it's gone.
+ fn sms_part(&self, id: String) -> Option<SmsPartData>;
}
/// Encrypts the device key at rest (Android: a Keystore key).
@@ -1039,6 +1115,55 @@ impl core::Platform for PlatformAdapter {
Err("the clipboard rejected it".into())
}
}
+ fn sms_threads(&self, limit: u32) -> Result<Vec<core::SmsThread>, String> {
+ Ok(self
+ .0
+ .sms_threads(limit)
+ .into_iter()
+ .map(|t| core::SmsThread {
+ id: t.id,
+ addresses: t.addresses,
+ names: t.names,
+ snippet: t.snippet,
+ date: t.date,
+ unread: t.unread,
+ photo: t.photo,
+ })
+ .collect())
+ }
+ fn sms_messages(
+ &self,
+ thread: &str,
+ before: Option<i64>,
+ limit: u32,
+ ) -> Result<Vec<core::SmsMessage>, String> {
+ Ok(self
+ .0
+ .sms_messages(thread.to_owned(), before, limit)
+ .into_iter()
+ .map(|m| core::SmsMessage {
+ id: m.id,
+ thread: m.thread,
+ address: m.address,
+ body: m.body,
+ date: m.date,
+ outgoing: m.outgoing,
+ status: m.status,
+ parts: m
+ .parts
+ .into_iter()
+ .map(|p| core::SmsPart { id: p.id, mime: p.mime, size: p.size })
+ .collect(),
+ })
+ .collect())
+ }
+ fn sms_send(&self, to: &[String], body: &str) -> Result<(), String> {
+ if self.0.sms_send(to.to_vec(), body.to_owned()) { Ok(()) } else { Err("not sent".into()) }
+ }
+ fn sms_part(&self, id: &str) -> Result<(String, Vec<u8>), String> {
+ let part = self.0.sms_part(id.to_owned()).ok_or("it's gone")?;
+ Ok((part.mime, part.data))
+ }
fn call_command(&self, id: &str, command: core::CallCommand) -> Result<(), String> {
let command = match command {
core::CallCommand::Answer => CallCommand::Answer,
@@ -1346,6 +1471,13 @@ impl NectarlinkNode {
self.run(async move { Ok(node.open_link(id, url).await?) }).await
}
+ /// This phone's messages changed (in `thread`, or anywhere when null):
+ /// PCs that show them catch up.
+ pub async fn sms_changed(&self, thread: Option<String>) {
+ let node = self.node.clone();
+ self.run(async move { node.sms_changed(thread).await }).await;
+ }
+
/// A call on this phone rang, was answered or ended: tells the PCs that
/// show calls (and are allowed them), now and when they connect during it.
pub async fn call_changed(&self, call: Call) -> Result<()> {
diff --git a/core/nectarlink-protocol/src/messages.rs b/core/nectarlink-protocol/src/messages.rs
index 5101d44..de252e4 100644
--- a/core/nectarlink-protocol/src/messages.rs
+++ b/core/nectarlink-protocol/src/messages.rs
@@ -45,6 +45,11 @@ pub mod types {
pub const PHOTOS_SENDING: &str = "photos.sending";
pub const CALL_STATE: &str = "call.state";
pub const CALL_ACTION: &str = "call.action";
+ pub const SMS_THREADS: &str = "sms.threads";
+ pub const SMS_MESSAGES: &str = "sms.messages";
+ pub const SMS_SEND: &str = "sms.send";
+ pub const SMS_PART: &str = "sms.part";
+ pub const SMS_CHANGED: &str = "sms.changed";
}
/// What kind of device this is.
@@ -458,6 +463,183 @@ pub struct PcPower {
/// The longest link sent, in bytes.
pub const LINK_MAX_BYTES: usize = 4096;
+// ---- Messages (docs/protocol/sms.md) ----
+
+pub mod sms {
+ /// Offered by phones that share their text messages.
+ pub const READ: &str = "sms.read";
+ /// Offered by phones that send texts when a PC asks.
+ pub const SEND: &str = "sms.send";
+ /// Offered by PCs that show text messages.
+ pub const SHOW: &str = "sms.show";
+ /// Most conversations or messages in one answer.
+ pub const MAX_PAGE: u32 = 100;
+ /// A text sent from a PC: at most this many bytes.
+ pub const MAX_SEND_BYTES: usize = 8 * 1024;
+ /// At most this many recipients.
+ pub const MAX_RECIPIENTS: usize = 20;
+ /// A picture in a message, fetched with `sms.part`: at most this many bytes.
+ pub const MAX_PART_BYTES: usize = 900 * 1024;
+ /// A contact's photo with a conversation: a JPEG of at most this many bytes.
+ pub const MAX_PHOTO_BYTES: usize = 16 * 1024;
+}
+
+/// A conversation, as `sms.threads` lists it.
+#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct SmsThread {
+ pub id: String,
+ /// The other people's numbers (more than one: a group).
+ pub addresses: Vec<String>,
+ /// Their contact names, in the same order (empty when not a contact).
+ #[serde(default)]
+ pub names: Vec<String>,
+ /// The latest message's text (or a description, like "Photo").
+ #[serde(default)]
+ pub snippet: String,
+ /// The latest message, in Unix milliseconds.
+ pub date: i64,
+ /// Unread messages.
+ #[serde(default)]
+ pub unread: u32,
+ /// The contact's photo (one-person conversations), a JPEG.
+ #[serde(default, skip_serializing_if = "Option::is_none", with = "serde_bytes")]
+ pub photo: Option<Vec<u8>>,
+}
+
+/// Never prints numbers, names or text (protocol v0 §11).
+impl std::fmt::Debug for SmsThread {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("SmsThread")
+ .field("id", &self.id)
+ .field("people", &self.addresses.len())
+ .field("unread", &self.unread)
+ .finish_non_exhaustive()
+ }
+}
+
+/// A picture (or other attachment) in a message.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct SmsPart {
+ /// Fetched with `sms.part`.
+ pub id: String,
+ pub mime: String,
+ #[serde(default)]
+ pub size: u64,
+}
+
+/// A message in a conversation.
+#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct SmsMessage {
+ pub id: String,
+ pub thread: String,
+ /// Who sent it (incoming), or the recipient (sent).
+ #[serde(default)]
+ pub address: String,
+ #[serde(default)]
+ pub body: String,
+ /// Unix milliseconds.
+ pub date: i64,
+ /// Sent from this phone (false: received).
+ #[serde(default)]
+ pub outgoing: bool,
+ /// For sent messages: `sent`, `pending` or `failed`.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub status: Option<String>,
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub parts: Vec<SmsPart>,
+}
+
+/// Never prints numbers or text (protocol v0 §11).
+impl std::fmt::Debug for SmsMessage {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("SmsMessage")
+ .field("id", &self.id)
+ .field("thread", &self.thread)
+ .field("outgoing", &self.outgoing)
+ .field("parts", &self.parts.len())
+ .finish_non_exhaustive()
+ }
+}
+
+/// Body of `sms.threads`: the latest conversations, newest first.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct SmsThreadsGet {
+ pub limit: u32,
+}
+
+/// Answer to `sms.threads`.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct SmsThreads {
+ pub threads: Vec<SmsThread>,
+}
+
+/// Body of `sms.messages`: a conversation's messages before `before`
+/// (Unix milliseconds; the latest when missing), newest first.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct SmsMessagesGet {
+ pub thread: String,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub before: Option<i64>,
+ pub limit: u32,
+}
+
+/// Answer to `sms.messages`.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct SmsMessages {
+ pub messages: Vec<SmsMessage>,
+}
+
+/// Body of `sms.send`.
+#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct SmsSend {
+ pub to: Vec<String>,
+ pub body: String,
+}
+
+/// Never prints numbers or text (protocol v0 §11).
+impl std::fmt::Debug for SmsSend {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("SmsSend").field("to", &self.to.len()).field("bytes", &self.body.len()).finish()
+ }
+}
+
+impl SmsSend {
+ pub fn is_valid(&self) -> bool {
+ (1..=sms::MAX_RECIPIENTS).contains(&self.to.len())
+ && self.to.iter().all(|a| (1..=64).contains(&a.trim().len()))
+ && !self.body.trim().is_empty()
+ && self.body.len() <= sms::MAX_SEND_BYTES
+ }
+}
+
+/// Body of `sms.part`: send this attachment.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct SmsPartGet {
+ pub id: String,
+}
+
+/// Answer to `sms.part`.
+#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct SmsPartData {
+ pub mime: String,
+ #[serde(with = "serde_bytes")]
+ pub data: Vec<u8>,
+}
+
+impl std::fmt::Debug for SmsPartData {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("SmsPartData").field("mime", &self.mime).field("bytes", &self.data.len()).finish()
+ }
+}
+
+/// Body of `sms.changed`: messages changed in this conversation (or in
+/// any, when missing).
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct SmsChanged {
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub thread: Option<String>,
+}
+
// ---- Calls (docs/protocol/calls.md) ----
pub mod calls {
@@ -928,6 +1110,17 @@ mod tests {
assert!(!format!("{:?}", offer("Secret")).contains("Secret"));
}
+ #[test]
+ fn texts_to_send_are_checked() {
+ let send = SmsSend { to: vec!["+15550100".into()], body: "On my way".into() };
+ assert!(send.is_valid());
+ assert!(!format!("{send:?}").contains("way"));
+ assert!(!SmsSend { to: vec![], ..send.clone() }.is_valid());
+ assert!(!SmsSend { body: " ".into(), ..send.clone() }.is_valid());
+ assert!(!SmsSend { body: "x".repeat(sms::MAX_SEND_BYTES + 1), ..send.clone() }.is_valid());
+ assert!(!SmsSend { to: vec!["1".into(); sms::MAX_RECIPIENTS + 1], ..send }.is_valid());
+ }
+
#[test]
fn calls_are_validated() {
let call = CallState {
diff --git a/desktop/app/build.rs b/desktop/app/build.rs
index a04bcbb..b865b7b 100644
--- a/desktop/app/build.rs
+++ b/desktop/app/build.rs
@@ -45,6 +45,7 @@ const QML: &[&str] = &[
"qml/components/TransferItem.qml",
"qml/components/Txt.qml",
"qml/pages/HomePage.qml",
+ "qml/pages/MessagesPage.qml",
"qml/pages/PairingPanel.qml",
"qml/pages/SettingsPage.qml",
"qml/pages/WelcomePage.qml",
@@ -192,6 +193,7 @@ fn main() {
"src/bridge/devices.rs",
"src/bridge/history.rs",
"src/bridge/media.rs",
+ "src/bridge/messages.rs",
"src/bridge/notifications.rs",
"src/bridge/pairing.rs",
"src/bridge/prefs.rs",
diff --git a/desktop/app/qml/Icons.qml b/desktop/app/qml/Icons.qml
index 2c186a3..fd52f63 100644
--- a/desktop/app/qml/Icons.qml
+++ b/desktop/app/qml/Icons.qml
@@ -7,6 +7,7 @@ import QtQuick
QtObject {
readonly property string home: "M3 11l9-7 9 7M5 10v10h14V10"
readonly property string messages: "M21 12a8 8 0 0 1-11.6 7.1L4 20l1-4.6A8 8 0 1 1 21 12z"
+ readonly property string person: "M12 12a4 4 0 1 0 0-8 4 4 0 0 0 0 8zM4 20a8 8 0 0 1 16 0"
readonly property string search: "M11 4a7 7 0 1 0 0 14a7 7 0 1 0 0-14zM20 20l-4-4"
readonly property string moon: "M20 14.5A8 8 0 0 1 9.5 4a8 8 0 1 0 10.5 10.5z"
readonly property string bell: "M6 8a6 6 0 1 1 12 0c0 7 3 8 3 8H3s3-1 3-8M10 20a2 2 0 0 0 4 0"
diff --git a/desktop/app/qml/MainWindow.qml b/desktop/app/qml/MainWindow.qml
index 6785abc..55e18ea 100644
--- a/desktop/app/qml/MainWindow.qml
+++ b/desktop/app/qml/MainWindow.qml
@@ -110,6 +110,12 @@ NativeWindow {
selected: window.page === "home"
onClicked: window.page = "home"
}
+ NavItem {
+ iconPath: Icons.messages
+ text: qsTr("Messages")
+ selected: window.page === "messages"
+ onClicked: window.page = "messages"
+ }
NavItem {
iconPath: Icons.settings
text: qsTr("Settings")
@@ -146,7 +152,8 @@ NativeWindow {
anchors.left: parent.left
anchors.leftMargin: Theme.contentPadding
anchors.verticalCenter: parent.verticalCenter
- text: window.page === "home" ? qsTr("Home") : qsTr("Settings")
+ text: window.page === "home" ? qsTr("Home")
+ : window.page === "messages" ? qsTr("Messages") : qsTr("Settings")
role: "headline"
size: 20
}
@@ -184,10 +191,17 @@ NativeWindow {
clip: true
HomePage {
+ id: homePage
anchors.fill: parent
active: window.page === "home"
onPairRequested: window.openPairing()
}
+ MessagesPage {
+ anchors.fill: parent
+ active: window.page === "messages"
+ deviceId: homePage.currentDeviceId
+ deviceName: homePage.currentDeviceName
+ }
SettingsPage {
anchors.fill: parent
active: window.page === "settings"
diff --git a/desktop/app/qml/pages/HomePage.qml b/desktop/app/qml/pages/HomePage.qml
index 8b33f31..6c0979e 100644
--- a/desktop/app/qml/pages/HomePage.qml
+++ b/desktop/app/qml/pages/HomePage.qml
@@ -142,9 +142,10 @@ Item {
required property real lastSeen
required property real pairedAt
- // Dropped files go to the device on screen.
- Binding { target: page; property: "currentDeviceId"; value: home.deviceId; when: home.visible }
- Binding { target: page; property: "currentDeviceName"; value: home.name; when: home.visible }
+ // Dropped files go to the device on screen (and Messages shows it).
+ // Kept while the page is hidden.
+ Binding { target: page; property: "currentDeviceId"; value: home.deviceId; when: home.visible; restoreMode: Binding.RestoreNone }
+ Binding { target: page; property: "currentDeviceName"; value: home.name; when: home.visible; restoreMode: Binding.RestoreNone }
Binding {
target: page
property: "currentCanReceive"
diff --git a/desktop/app/qml/pages/MessagesPage.qml b/desktop/app/qml/pages/MessagesPage.qml
new file mode 100644
index 0000000..3b85256
--- /dev/null
+++ b/desktop/app/qml/pages/MessagesPage.qml
@@ -0,0 +1,566 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+import QtQuick
+import app.nectarlink
+
+// Messages: the phone's conversations on the left, the open one on the
+// right, and a box to text from the PC (sent through the phone).
+Item {
+ id: page
+ property bool active: true
+ // The phone shown (the one on Home).
+ property string deviceId
+ property string deviceName
+ // Writing to someone new (no conversation open).
+ property bool composing: false
+
+ readonly property var threads: { try { return JSON.parse(Messages.threads) } catch (e) { return [] } }
+ readonly property var messages: { try { return JSON.parse(Messages.messages) } catch (e) { return [] } }
+ readonly property var openThread: threads.find(t => t.id === Messages.thread) || null
+ readonly property bool ready: Messages.status === "ready"
+
+ opacity: active ? 1 : 0
+ visible: opacity > 0
+ Behavior on opacity { NumberAnimation { duration: Theme.fadeNormal } }
+ transform: Translate {
+ y: page.active || Theme.reduceMotion ? 0 : 12
+ Behavior on y { SpringAnimation { spring: Theme.springGentle; damping: Theme.dampingGentle } }
+ }
+
+ function load() {
+ if (active && deviceId.length > 0)
+ Messages.open(deviceId)
+ }
+ onActiveChanged: load()
+ onDeviceIdChanged: { composing = false; load() }
+
+ // "14:05", "Tue", or a date.
+ function shortTime(ms) {
+ const date = new Date(ms)
+ const now = new Date()
+ if (date.toDateString() === now.toDateString())
+ return date.toLocaleTimeString(Qt.locale(), Locale.ShortFormat)
+ if (now - date < 6 * 24 * 3600 * 1000)
+ return date.toLocaleDateString(Qt.locale(), "ddd")
+ return date.toLocaleDateString(Qt.locale(), Locale.ShortFormat)
+ }
+
+ // ---- No phone, or messages not available ----
+ Column {
+ anchors.centerIn: parent
+ width: Math.min(parent.width - Theme.contentPadding * 2, 420)
+ spacing: 12
+ visible: !list.visible && (page.deviceId.length === 0 || Messages.status !== "loading")
+ Icon {
+ anchors.horizontalCenter: parent.horizontalCenter
+ width: 40; height: 40
+ stroke: 1.5
+ path: Icons.messages
+ color: Theme.surfaceContentVariant
+ }
+ Txt {
+ width: parent.width
+ horizontalAlignment: Text.AlignHCenter
+ role: "title"
+ text: page.deviceId.length === 0 ? qsTr("Text from your PC")
+ : Messages.status === "offline" ? qsTr("%1 isn't connected").arg(page.deviceName)
+ : Messages.status === "off" ? qsTr("Messages are off for %1").arg(page.deviceName)
+ : Messages.status === "unsupported" ? qsTr("Allow texting on %1").arg(page.deviceName)
+ : qsTr("Couldn't load messages")
+ }
+ Txt {
+ width: parent.width
+ horizontalAlignment: Text.AlignHCenter
+ wrapMode: Text.WordWrap
+ role: "body"
+ muted: true
+ text: page.deviceId.length === 0 ? qsTr("Pair your phone to read and send texts here.")
+ : Messages.status === "offline" ? qsTr("Your conversations show up here when it's back.")
+ : Messages.status === "off" ? qsTr("Turn on Messages for this phone, here in Settings and in the Nectarlink app on the phone.")
+ : Messages.status === "unsupported" ? qsTr("In the Nectarlink app on your phone, tap Allow on “Text from your PC”.")
+ : qsTr("Something went wrong reading them from the phone.")
+ }
+ Button {
+ anchors.horizontalCenter: parent.horizontalCenter
+ visible: page.deviceId.length > 0 && Messages.status === "failed"
+ variant: "tonal"
+ text: qsTr("Try again")
+ onClicked: page.load()
+ }
+ }
+
+ Spinner {
+ anchors.centerIn: parent
+ visible: Messages.status === "loading" && page.threads.length === 0
+ }
+
+ // ---- Conversations ----
+ Item {
+ id: list
+ visible: page.threads.length > 0 || (page.ready && page.deviceId.length > 0)
+ width: Math.min(340, Math.max(260, page.width * 0.34))
+ height: parent.height
+
+ Item {
+ id: listHeader
+ width: parent.width
+ height: 56
+ Txt {
+ anchors.left: parent.left
+ anchors.leftMargin: 20
+ anchors.verticalCenter: parent.verticalCenter
+ text: qsTr("Conversations")
+ role: "title"
+ }
+ IconButton {
+ anchors.right: parent.right
+ anchors.rightMargin: 10
+ anchors.verticalCenter: parent.verticalCenter
+ iconPath: Icons.plus
+ label: qsTr("New message")
+ tonal: page.composing
+ enabled: page.ready
+ onClicked: {
+ Messages.closeThread()
+ page.composing = true
+ toField.forceActiveFocus()
+ }
+ }
+ }
+
+ ListView {
+ id: threadList
+ anchors.top: listHeader.bottom
+ anchors.bottom: parent.bottom
+ width: parent.width
+ clip: true
+ boundsBehavior: Flickable.StopAtBounds
+ model: page.threads
+ delegate: ThreadRow {
+ width: threadList.width
+ thread: modelData
+ }
+ Txt {
+ anchors.centerIn: parent
+ visible: page.ready && page.threads.length === 0
+ role: "body"
+ muted: true
+ text: qsTr("No conversations yet.")
+ }
+ }
+ Divider { anchors.right: parent.right; width: 1; height: parent.height }
+ }
+
+ // ---- The open conversation, or a new one ----
+ Item {
+ id: chat
+ anchors.left: list.right
+ anchors.right: parent.right
+ height: parent.height
+ visible: list.visible
+
+ Txt {
+ anchors.centerIn: parent
+ visible: !page.openThread && !page.composing && list.visible
+ role: "body"
+ muted: true
+ text: qsTr("Choose a conversation, or start a new one.")
+ }
+
+ Item {
+ id: chatHeader
+ visible: !!page.openThread || page.composing
+ width: parent.width
+ height: 64
+ Column {
+ anchors.left: parent.left
+ anchors.leftMargin: 24
+ anchors.right: parent.right
+ anchors.rightMargin: 24
+ anchors.verticalCenter: parent.verticalCenter
+ spacing: 2
+ visible: !page.composing
+ Txt {
+ width: parent.width
+ text: page.openThread ? page.openThread.title : ""
+ role: "title"
+ elide: Text.ElideRight
+ }
+ Txt {
+ width: parent.width
+ visible: page.openThread && page.openThread.title !== page.openThread.addresses
+ text: page.openThread ? page.openThread.addresses : ""
+ role: "bodySmall"
+ muted: true
+ elide: Text.ElideRight
+ }
+ }
+ // New message: who to.
+ Row {
+ anchors.left: parent.left
+ anchors.leftMargin: 24
+ anchors.right: parent.right
+ anchors.rightMargin: 24
+ anchors.verticalCenter: parent.verticalCenter
+ spacing: 12
+ visible: page.composing
+ Txt { anchors.verticalCenter: parent.verticalCenter; text: qsTr("To"); role: "title" }
+ TextInput {
+ id: toField
+ anchors.verticalCenter: parent.verticalCenter
+ width: parent.width - 40
+ font.family: Theme.fontUi
+ font.pixelSize: 15
+ color: Theme.surfaceContent
+ selectionColor: Theme.primaryContainer
+ selectedTextColor: Theme.primaryContainerContent
+ inputMethodHints: Qt.ImhDialableCharactersOnly
+ clip: true
+ Accessible.name: qsTr("Phone number")
+ Keys.onReturnPressed: composer.focusText()
+ Txt {
+ anchors.verticalCenter: parent.verticalCenter
+ visible: toField.text.length === 0
+ role: "body"
+ muted: true
+ text: qsTr("Phone number")
+ }
+ }
+ }
+ Divider { anchors.bottom: parent.bottom; width: parent.width }
+ }
+
+ ListView {
+ id: messageList
+ anchors.top: chatHeader.bottom
+ anchors.bottom: composer.top
+ anchors.bottomMargin: 8
+ width: parent.width
+ visible: !!page.openThread
+ clip: true
+ spacing: 6
+ // A short conversation sits at the bottom, by the box.
+ topMargin: Math.max(16, height - contentHeight - bottomMargin)
+ bottomMargin: 8
+ boundsBehavior: Flickable.StopAtBounds
+ model: page.messages
+ // The latest at the bottom; scrolling up loads older ones.
+ property int lastCount: 0
+ onCountChanged: {
+ const grewAtTop = count > lastCount && lastCount > 0 && Messages.loadingOlder === false && atYBeginning
+ if (!grewAtTop)
+ Qt.callLater(positionViewAtEnd)
+ lastCount = count
+ }
+ onAtYBeginningChanged: if (atYBeginning && Messages.more && count > 0) Messages.loadOlder()
+ header: Item {
+ width: messageList.width
+ height: Messages.loadingOlder ? 40 : 0
+ Spinner { anchors.centerIn: parent; visible: Messages.loadingOlder }
+ }
+ delegate: Bubble {
+ width: messageList.width
+ message: modelData
+ }
+ Txt {
+ anchors.centerIn: parent
+ width: Math.min(parent.width - 48, 420)
+ horizontalAlignment: Text.AlignHCenter
+ wrapMode: Text.WordWrap
+ visible: page.openThread && page.messages.length === 0 && page.ready
+ role: "body"
+ muted: true
+ text: qsTr("No messages to show. Android keeps texts with one-time codes from other apps for a few hours.")
+ }
+ }
+
+ // Writing a text.
+ Rectangle {
+ id: composer
+ visible: !!page.openThread || page.composing
+ readonly property bool group: !!page.openThread && page.openThread.group
+ readonly property bool canSend: page.ready && !Messages.sending && !group
+ && input.text.trim().length > 0 && (!page.composing || toField.text.trim().length > 0)
+ function focusText() { input.forceActiveFocus() }
+ function send() {
+ if (!canSend)
+ return
+ if (page.composing)
+ Messages.sendTo(toField.text, input.text)
+ else
+ Messages.send(input.text)
+ input.text = ""
+ page.composing = false
+ toField.text = ""
+ }
+ anchors.left: parent.left
+ anchors.right: parent.right
+ anchors.bottom: parent.bottom
+ anchors.margins: 16
+ height: Math.min(Math.max(input.contentHeight + 22, 48), 160)
+ radius: Theme.graphite ? Theme.radiusSm : 24
+ color: Theme.graphite ? "transparent" : Theme.surfaceContainerHighest
+ border.width: input.activeFocus ? 2 : 1
+ border.color: input.activeFocus ? Theme.primary : Theme.outlineVariant
+
+ Flickable {
+ id: inputScroll
+ anchors.left: parent.left
+ anchors.leftMargin: 18
+ anchors.right: sendButton.left
+ anchors.rightMargin: 8
+ anchors.top: parent.top
+ anchors.topMargin: 11
+ anchors.bottom: parent.bottom
+ anchors.bottomMargin: 11
+ contentHeight: input.contentHeight
+ clip: true
+ boundsBehavior: Flickable.StopAtBounds
+ TextEdit {
+ id: input
+ width: inputScroll.width
+ wrapMode: TextEdit.Wrap
+ readOnly: composer.group
+ font.family: Theme.fontUi
+ font.pixelSize: 14
+ color: Theme.surfaceContent
+ selectionColor: Theme.primaryContainer
+ selectedTextColor: Theme.primaryContainerContent
+ Accessible.name: qsTr("Text message")
+ // Enter sends; Shift+Enter starts a new line.
+ Keys.onPressed: (event) => {
+ if ((event.key === Qt.Key_Return || event.key === Qt.Key_Enter) && !(event.modifiers & Qt.ShiftModifier)) {
+ composer.send()
+ event.accepted = true
+ }
+ }
+ onCursorRectangleChanged: {
+ if (cursorRectangle.y < inputScroll.contentY)
+ inputScroll.contentY = cursorRectangle.y
+ else if (cursorRectangle.y + cursorRectangle.height > inputScroll.contentY + inputScroll.height)
+ inputScroll.contentY = cursorRectangle.y + cursorRectangle.height - inputScroll.height
+ }
+ Txt {
+ visible: input.text.length === 0
+ role: "body"
+ muted: true
+ text: composer.group ? qsTr("Group texts can't be sent from the PC yet")
+ : qsTr("Text message")
+ }
+ }
+ }
+ IconButton {
+ id: sendButton
+ anchors.right: parent.right
+ anchors.rightMargin: 6
+ anchors.bottom: parent.bottom
+ anchors.bottomMargin: 6
+ iconPath: Icons.send
+ label: qsTr("Send")
+ tonal: composer.canSend
+ enabled: composer.canSend
+ onClicked: composer.send()
+ }
+ Spinner {
+ anchors.centerIn: sendButton
+ visible: Messages.sending
+ }
+ }
+ }
+
+ // A conversation in the list.
+ component ThreadRow: Item {
+ id: row
+ property var thread
+ readonly property bool selected: thread.id === Messages.thread
+ height: 72
+ Accessible.role: Accessible.ListItem
+ Accessible.name: thread.title + ". " + thread.snippet
+ Accessible.onPressAction: open()
+ function open() {
+ page.composing = false
+ Messages.openThread(thread.id)
+ }
+
+ Rectangle {
+ anchors.fill: parent
+ anchors.leftMargin: 8
+ anchors.rightMargin: 8
+ radius: Theme.radiusLg
+ color: row.selected ? Theme.secondaryContainer
+ : rowHover.hovered ? Qt.rgba(Theme.surfaceContent.r, Theme.surfaceContent.g, Theme.surfaceContent.b, 0.06)
+ : "transparent"
+ Behavior on color { ColorAnimation { duration: Theme.fadeFast } }
+ }
+ Item {
+ id: face
+ x: 20
+ anchors.verticalCenter: parent.verticalCenter
+ width: 40; height: 40
+ RoundedImage {
+ anchors.fill: parent
+ radius: width / 2
+ visible: row.thread.photo.length > 0 && status === Image.Ready
+ source: row.thread.photo
+ sourceSize: Qt.size(80, 80)
+ fillMode: Image.PreserveAspectCrop
+ }
+ Avatar {
+ anchors.fill: parent
+ visible: row.thread.photo.length === 0
+ // A contact's initial; a number (no letter to show) or a group gets an icon.
+ readonly property bool named: !/^[\d+(#*]/.test(row.thread.title)
+ name: row.thread.group || !named ? "" : row.thread.title
+ iconPath: row.thread.group ? Icons.messages : named ? "" : Icons.person
+ emphasized: row.thread.unread > 0
+ }
+ }
+ Column {
+ anchors.left: face.right
+ anchors.leftMargin: 12
+ anchors.right: parent.right
+ anchors.rightMargin: 20
+ anchors.verticalCenter: parent.verticalCenter
+ spacing: 2
+ Item {
+ width: parent.width
+ height: name.height
+ Txt {
+ id: name
+ anchors.left: parent.left
+ anchors.right: when.left
+ anchors.rightMargin: 8
+ text: row.thread.title
+ role: "body"
+ weight: row.thread.unread > 0 ? 650 : 500
+ elide: Text.ElideRight
+ }
+ Txt {
+ id: when
+ anchors.right: parent.right
+ anchors.baseline: name.baseline
+ text: page.shortTime(row.thread.date)
+ role: "bodySmall"
+ color: row.thread.unread > 0 ? Theme.primary : Theme.surfaceContentVariant
+ }
+ }
+ Item {
+ width: parent.width
+ height: snippet.height
+ Txt {
+ id: snippet
+ anchors.left: parent.left
+ anchors.right: badge.visible ? badge.left : parent.right
+ anchors.rightMargin: 8
+ text: row.thread.snippet
+ role: "bodySmall"
+ muted: row.thread.unread === 0
+ maximumLineCount: 1
+ elide: Text.ElideRight
+ }
+ Rectangle {
+ id: badge
+ anchors.right: parent.right
+ anchors.verticalCenter: snippet.verticalCenter
+ visible: row.thread.unread > 0
+ width: Math.max(20, count.implicitWidth + 10)
+ height: 20
+ radius: 10
+ color: Theme.primary
+ Txt {
+ id: count
+ anchors.centerIn: parent
+ text: row.thread.unread
+ role: "label"
+ size: 11
+ color: Theme.primaryContent
+ }
+ }
+ }
+ }
+ HoverHandler { id: rowHover; cursorShape: Qt.PointingHandCursor }
+ TapHandler { onTapped: row.open() }
+ }
+
+ // A message: right-aligned when sent from the phone.
+ component Bubble: Item {
+ id: bubble
+ property var message
+ readonly property bool mine: message.outgoing
+ readonly property real maxWidth: Math.min(width * 0.72, 520)
+ height: content.height + meta.height + 4
+
+ Rectangle {
+ id: content
+ anchors.right: bubble.mine ? parent.right : undefined
+ anchors.left: bubble.mine ? undefined : parent.left
+ anchors.leftMargin: 24
+ anchors.rightMargin: 24
+ width: Math.max(pictures.width, Math.min(text.implicitWidth, bubble.maxWidth - 28) + 28)
+ height: pictures.height + (text.visible ? text.height + 18 : 0)
+ radius: 18
+ color: bubble.mine ? Theme.primaryContainer : Theme.surfaceContainerHigh
+ border.width: Theme.graphite ? 1 : 0
+ border.color: Theme.outlineVariant
+ Column {
+ id: pictures
+ width: bubble.message.images.length > 0 ? Math.min(260, bubble.maxWidth) : 0
+ Repeater {
+ model: bubble.message.images
+ delegate: Item {
+ required property string modelData
+ width: pictures.width
+ height: modelData.length > 0 && picture.status === Image.Ready
+ ? Math.min(320, width * picture.implicitImageHeight / Math.max(1, picture.implicitImageWidth))
+ : 140
+ RoundedImage {
+ id: picture
+ anchors.fill: parent
+ radius: 18
+ source: parent.modelData
+ fillMode: Image.PreserveAspectCrop
+ sourceSize.width: 520
+ }
+ Spinner { anchors.centerIn: parent; visible: parent.modelData.length === 0 }
+ TapHandler { onTapped: if (parent.modelData.length > 0) Qt.openUrlExternally(parent.modelData) }
+ HoverHandler { cursorShape: parent.modelData.length > 0 ? Qt.PointingHandCursor : Qt.ArrowCursor }
+ }
+ }
+ }
+ TextEdit {
+ id: text
+ anchors.top: pictures.bottom
+ anchors.topMargin: 9
+ x: 14
+ width: Math.min(implicitWidth, bubble.maxWidth - 28)
+ visible: bubble.message.body.length > 0 || bubble.message.attachments > 0
+ text: bubble.message.body.length > 0 ? bubble.message.body
+ : qsTr("Attachment (open it on the phone)")
+ readOnly: true
+ selectByMouse: true
+ wrapMode: TextEdit.Wrap
+ textFormat: TextEdit.PlainText
+ font.family: Theme.fontUi
+ font.pixelSize: 14
+ font.italic: bubble.message.body.length === 0
+ color: bubble.mine ? Theme.primaryContainerContent : Theme.surfaceContent
+ selectionColor: Theme.primary
+ selectedTextColor: Theme.primaryContent
+ }
+ }
+ Txt {
+ id: meta
+ anchors.top: content.bottom
+ anchors.topMargin: 3
+ anchors.right: bubble.mine ? content.right : undefined
+ anchors.left: bubble.mine ? undefined : content.left
+ anchors.leftMargin: 6
+ anchors.rightMargin: 6
+ role: "bodySmall"
+ size: 11
+ color: bubble.message.status === "failed" ? Theme.error : Theme.surfaceContentVariant
+ text: bubble.message.status === "failed" ? qsTr("Not sent")
+ : bubble.message.status === "pending" ? qsTr("Sending…")
+ : page.shortTime(bubble.message.date)
+ }
+ }
+}
diff --git a/desktop/app/src/bridge/messages.rs b/desktop/app/src/bridge/messages.rs
new file mode 100644
index 0000000..8660a59
--- /dev/null
+++ b/desktop/app/src/bridge/messages.rs
@@ -0,0 +1,146 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! `Messages`: a phone's conversations and the open one's messages for the
+//! Messages page (JSON arrays QML reads), and what the page asks of them.
+
+use std::pin::Pin;
+
+use cxx_qt::{CxxQtType, Threading};
+use cxx_qt_lib::QString;
+
+use crate::{messages, state::Changes};
+
+#[cxx_qt::bridge]
+pub mod qobject {
+ unsafe extern "C++" {
+ include!("cxx-qt-lib/qstring.h");
+ type QString = cxx_qt_lib::QString;
+ }
+
+ unsafe extern "RustQt" {
+ #[qobject]
+ #[qml_element]
+ #[qml_singleton]
+ /// The phone shown.
+ #[qproperty(QString, device)]
+ /// "idle", "loading", "ready", "offline", "off", "unsupported" or "failed".
+ #[qproperty(QString, status)]
+ /// Conversations, newest first (JSON).
+ #[qproperty(QString, threads)]
+ /// The open conversation's ID ("" for none).
+ #[qproperty(QString, thread)]
+ /// Its messages, oldest first (JSON).
+ #[qproperty(QString, messages)]
+ /// Older messages can be loaded.
+ #[qproperty(bool, more)]
+ #[qproperty(bool, loading_older, cxx_name = "loadingOlder")]
+ #[qproperty(bool, sending)]
+ type Messages = super::MessagesRust;
+ }
+
+ impl cxx_qt::Threading for Messages {}
+ impl cxx_qt::Initialize for Messages {}
+
+ unsafe extern "RustQt" {
+ /// Shows a phone's messages (reloads when it's the one shown).
+ #[qinvokable]
+ fn open(self: &Messages, device: &QString);
+ #[qinvokable]
+ #[cxx_name = "openThread"]
+ fn open_thread(self: &Messages, thread: &QString);
+ #[qinvokable]
+ #[cxx_name = "closeThread"]
+ fn close_thread(self: &Messages);
+ #[qinvokable]
+ #[cxx_name = "loadOlder"]
+ fn load_older(self: &Messages);
+ /// Sends a text in the open conversation.
+ #[qinvokable]
+ fn send(self: &Messages, body: &QString);
+ /// Sends a text to a number, starting a conversation.
+ #[qinvokable]
+ #[cxx_name = "sendTo"]
+ fn send_to(self: &Messages, to: &QString, body: &QString);
+ }
+}
+
+#[derive(Default)]
+pub struct MessagesRust {
+ device: QString,
+ status: QString,
+ threads: QString,
+ thread: QString,
+ messages: QString,
+ more: bool,
+ loading_older: bool,
+ sending: bool,
+ /// What was last shown, to skip refreshes that change nothing.
+ last: Option<messages::View>,
+}
+
+impl cxx_qt::Initialize for qobject::Messages {
+ fn initialize(mut self: Pin<&mut Self>) {
+ self.as_mut().set_status(QString::from("idle"));
+ self.as_mut().set_threads(QString::from("[]"));
+ self.as_mut().set_messages(QString::from("[]"));
+ super::subscribe(self.qt_thread(), Changes::MESSAGES, Self::refresh);
+ self.refresh();
+ }
+}
+
+impl qobject::Messages {
+ fn refresh(mut self: Pin<&mut Self>) {
+ let view = messages::view();
+ if self.rust().last.as_ref() == Some(&view) {
+ return;
+ }
+ let last = self.rust().last.clone();
+ let differs = |f: fn(&messages::View) -> String| last.as_ref().is_none_or(|l| f(l) != f(&view));
+ self.as_mut().set_device(QString::from(&view.device.map(|d| d.to_string()).unwrap_or_default()));
+ self.as_mut().set_status(QString::from(view.status.as_str()));
+ if differs(|v| v.threads.to_string()) {
+ self.as_mut().set_threads(QString::from(&view.threads.to_string()));
+ }
+ self.as_mut().set_thread(QString::from(view.thread.as_deref().unwrap_or_default()));
+ if differs(|v| v.messages.to_string()) {
+ self.as_mut().set_messages(QString::from(&view.messages.to_string()));
+ }
+ self.as_mut().set_more(view.more);
+ self.as_mut().set_loading_older(view.loading_older);
+ self.as_mut().set_sending(view.sending);
+ self.as_mut().rust_mut().last = Some(view);
+ }
+
+ pub fn open(&self, device: &QString) {
+ if let Some(device) = super::parse_device(device) {
+ messages::open_device(device);
+ }
+ }
+
+ pub fn open_thread(&self, thread: &QString) {
+ messages::open_thread(String::from(thread));
+ }
+
+ pub fn close_thread(&self) {
+ messages::close_thread();
+ }
+
+ pub fn load_older(&self) {
+ messages::load_older();
+ }
+
+ pub fn send(&self, body: &QString) {
+ let body = String::from(body);
+ if !body.trim().is_empty() {
+ messages::send(body);
+ }
+ }
+
+ pub fn send_to(&self, to: &QString, body: &QString) {
+ let (to, body) = (String::from(to), String::from(body));
+ let to: Vec<String> =
+ to.split([',', ';']).map(str::trim).filter(|t| !t.is_empty()).map(Into::into).collect();
+ if !to.is_empty() && !body.trim().is_empty() {
+ messages::send_to(to, body);
+ }
+ }
+}
diff --git a/desktop/app/src/bridge/mod.rs b/desktop/app/src/bridge/mod.rs
index c6332bf..bee0847 100644
--- a/desktop/app/src/bridge/mod.rs
+++ b/desktop/app/src/bridge/mod.rs
@@ -14,6 +14,8 @@ pub mod history;
#[allow(unsafe_code)]
pub mod media;
#[allow(unsafe_code)]
+pub mod messages;
+#[allow(unsafe_code)]
pub mod native;
#[allow(unsafe_code)]
pub mod notifications;
diff --git a/desktop/app/src/core_host.rs b/desktop/app/src/core_host.rs
index e7ba838..01291a8 100644
--- a/desktop/app/src/core_host.rs
+++ b/desktop/app/src/core_host.rs
@@ -100,6 +100,7 @@ async fn run(data_dir: PathBuf, platform: Arc<dyn Platform>) {
"pc.power".into(),
nectarlink_core::PHOTOS_SHOW.into(),
nectarlink_core::CALLS_SHOW.into(),
+ nectarlink_core::SMS_SHOW.into(),
];
let node = match Node::start(config, platform).await {
Ok(node) => node,
@@ -148,6 +149,7 @@ async fn run(data_dir: PathBuf, platform: Arc<dyn Platform>) {
crate::clipboard::on_event(&event);
crate::photos::on_event(&event);
crate::calls::on_event(&event);
+ crate::messages::on_event(&event);
crate::transfers::on_event(&event);
crate::send_to::on_event(&event);
crate::battery::on_event(&event);
diff --git a/desktop/app/src/main.rs b/desktop/app/src/main.rs
index dfc1db3..b0292e6 100644
--- a/desktop/app/src/main.rs
+++ b/desktop/app/src/main.rs
@@ -20,6 +20,7 @@ mod links;
mod logging;
mod mark;
mod media;
+mod messages;
mod notification_store;
mod notifications;
mod palette;
diff --git a/desktop/app/src/messages.rs b/desktop/app/src/messages.rs
new file mode 100644
index 0000000..f8b67a9
--- /dev/null
+++ b/desktop/app/src/messages.rs
@@ -0,0 +1,500 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! Text messages on the PC (docs/protocol/sms.md): a phone's conversations
+//! and the open one's messages, read through the phone on demand and kept
+//! only in memory. Texts sent from here go out through the phone.
+
+use std::{collections::HashMap, path::PathBuf, sync::Mutex};
+
+use nectarlink_core::{DeviceId, Error, LinkState, NodeEvent, SmsMessage, SmsThread};
+use serde_json::{Value, json};
+
+use crate::{core_host, state::Changes};
+
+/// Conversations listed, and messages read at a time.
+const THREADS: u32 = 60;
+const PAGE: u32 = 30;
+
+/// What the Messages page can show.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
+pub enum Status {
+ /// No phone chosen yet.
+ #[default]
+ Idle,
+ Loading,
+ Ready,
+ /// The phone isn't connected.
+ Offline,
+ /// Messages are off for this phone (here or there).
+ Off,
+ /// The phone doesn't share messages (no permission, or an old app).
+ Unsupported,
+ Failed,
+}
+
+impl Status {
+ pub fn as_str(self) -> &'static str {
+ match self {
+ Status::Idle => "idle",
+ Status::Loading => "loading",
+ Status::Ready => "ready",
+ Status::Offline => "offline",
+ Status::Off => "off",
+ Status::Unsupported => "unsupported",
+ Status::Failed => "failed",
+ }
+ }
+
+ fn of(error: &Error) -> Status {
+ match error {
+ Error::Denied => Status::Off,
+ Error::Unsupported => Status::Unsupported,
+ Error::Offline | Error::NotPaired | Error::Timeout => Status::Offline,
+ _ => Status::Failed,
+ }
+ }
+}
+
+#[derive(Debug, Default)]
+struct State {
+ device: Option<DeviceId>,
+ status: Status,
+ threads: Vec<SmsThread>,
+ /// The open conversation.
+ thread: Option<String>,
+ /// Its messages, newest first.
+ messages: Vec<SmsMessage>,
+ /// Older messages may exist.
+ more: bool,
+ loading_older: bool,
+ sending: bool,
+ /// Pictures fetched, by part ID.
+ pictures: HashMap<String, PathBuf>,
+ /// Contact photos saved, by thread ID.
+ photos: HashMap<String, PathBuf>,
+ /// Bumped when the phone changes, so late answers are dropped.
+ generation: u64,
+}
+
+static STATE: Mutex<Option<State>> = Mutex::new(None);
+
+fn state<T>(f: impl FnOnce(&mut State) -> T) -> T {
+ f(STATE.lock().unwrap_or_else(|e| e.into_inner()).get_or_insert_default())
+}
+
+fn changed() {
+ core_host::host().hub.changed(Changes::MESSAGES);
+}
+
+fn files_dir() -> PathBuf {
+ crate::notifications::images_dir()
+}
+
+// ---- What the page shows ----
+
+/// Everything the page shows, for QML.
+#[derive(Debug, Clone, PartialEq)]
+pub struct View {
+ pub device: Option<DeviceId>,
+ pub status: Status,
+ pub threads: Value,
+ pub thread: Option<String>,
+ pub messages: Value,
+ pub more: bool,
+ pub loading_older: bool,
+ pub sending: bool,
+}
+
+pub fn view() -> View {
+ state(|s| View {
+ device: s.device,
+ status: s.status,
+ threads: Value::Array(s.threads.iter().map(|t| thread_json(t, s.photos.get(&t.id))).collect()),
+ thread: s.thread.clone(),
+ messages: Value::Array(s.messages.iter().rev().map(|m| message_json(m, &s.pictures)).collect()),
+ more: s.more,
+ loading_older: s.loading_older,
+ sending: s.sending,
+ })
+}
+
+/// Who a conversation is with: contact names, or numbers.
+pub fn title_of(thread: &SmsThread) -> String {
+ thread
+ .addresses
+ .iter()
+ .enumerate()
+ .map(|(i, address)| thread.names.get(i).filter(|n| !n.trim().is_empty()).unwrap_or(address).clone())
+ .collect::<Vec<_>>()
+ .join(", ")
+}
+
+fn thread_json(t: &SmsThread, photo: Option<&PathBuf>) -> Value {
+ json!({
+ "id": t.id,
+ "title": title_of(t),
+ "addresses": t.addresses.join(", "),
+ "snippet": t.snippet,
+ "date": t.date,
+ "unread": t.unread,
+ "group": t.addresses.len() > 1,
+ "photo": photo.map(|p| crate::icons::file_url(p)).unwrap_or_default(),
+ })
+}
+
+fn message_json(m: &SmsMessage, pictures: &HashMap<String, PathBuf>) -> Value {
+ let images: Vec<Value> = m
+ .parts
+ .iter()
+ .filter(|p| p.mime.starts_with("image/"))
+ .map(|p| json!(pictures.get(&p.id).map(|f| crate::icons::file_url(f)).unwrap_or_default()))
+ .collect();
+ let others = m.parts.iter().filter(|p| !p.mime.starts_with("image/")).count();
+ json!({
+ "id": m.id,
+ "body": m.body,
+ "date": m.date,
+ "outgoing": m.outgoing,
+ "status": m.status.clone().unwrap_or_default(),
+ "images": images,
+ "attachments": others,
+ })
+}
+
+// ---- What the page asks ----
+
+/// Shows `device`'s messages (again: reloads).
+pub fn open_device(device: DeviceId) {
+ let same = state(|s| {
+ let same = s.device == Some(device);
+ if !same {
+ *s = State { device: Some(device), generation: s.generation + 1, ..State::default() };
+ }
+ same
+ });
+ if !same {
+ changed();
+ }
+ load_threads();
+}
+
+pub fn load_threads() {
+ let Some((device, generation)) = state(|s| {
+ if s.threads.is_empty() {
+ s.status = Status::Loading;
+ }
+ s.device.map(|d| (d, s.generation))
+ }) else {
+ return;
+ };
+ changed();
+ let Some(node) = core_host::node() else { return };
+ core_host::spawn(async move {
+ let result = node.sms_threads(device, THREADS).await;
+ let photos = match &result {
+ Ok(threads) => save_photos(device, threads),
+ Err(_) => HashMap::new(),
+ };
+ state(|s| {
+ if s.generation != generation {
+ return;
+ }
+ match result {
+ Ok(threads) => {
+ s.threads = threads;
+ s.photos.extend(photos);
+ s.status = Status::Ready;
+ }
+ Err(e) => {
+ tracing::debug!(error = %e, "can't list conversations");
+ s.status = Status::of(&e);
+ }
+ }
+ });
+ changed();
+ open_pending();
+ });
+}
+
+/// Contact photos as files, for QML.
+fn save_photos(device: DeviceId, threads: &[SmsThread]) -> HashMap<String, PathBuf> {
+ let dir = files_dir();
+ if std::fs::create_dir_all(&dir).is_err() {
+ return HashMap::new();
+ }
+ threads
+ .iter()
+ .filter_map(|t| {
+ let photo = t.photo.as_ref()?;
+ let path = dir.join(format!(
+ "sms-{:016x}.jpg",
+ crate::photos::fingerprint(&format!("{device} {}", t.id))
+ ^ crate::photos::fingerprint_bytes(photo)
+ ));
+ if !path.exists() {
+ std::fs::write(&path, photo).ok()?;
+ }
+ Some((t.id.clone(), path))
+ })
+ .collect()
+}
+
+/// Opens a conversation: its latest messages.
+pub fn open_thread(thread: String) {
+ state(|s| {
+ if s.thread.as_deref() != Some(&thread) {
+ s.thread = Some(thread);
+ s.messages.clear();
+ s.more = false;
+ }
+ });
+ changed();
+ load_messages(None);
+}
+
+/// The open conversation's older messages.
+pub fn load_older() {
+ let before = state(|s| {
+ if s.loading_older || !s.more {
+ return None;
+ }
+ s.loading_older = true;
+ s.messages.last().map(|m| m.date)
+ });
+ if before.is_some() {
+ changed();
+ load_messages(before);
+ }
+}
+
+fn load_messages(before: Option<i64>) {
+ let Some((device, thread, generation)) = state(|s| Some((s.device?, s.thread.clone()?, s.generation)))
+ else {
+ return;
+ };
+ let Some(node) = core_host::node() else { return };
+ core_host::spawn(async move {
+ let result = node.sms_messages(device, thread.clone(), before, PAGE).await;
+ let wanted = state(|s| {
+ s.loading_older = false;
+ if s.generation != generation || s.thread.as_deref() != Some(&thread) {
+ return Vec::new();
+ }
+ match result {
+ Ok(page) => {
+ let full = page.len() as u32 >= PAGE;
+ if before.is_none() {
+ // The latest page replaces what was there, keeping
+ // older pages already read.
+ let oldest = page.last().map(|m| m.date).unwrap_or(i64::MAX);
+ let older: Vec<SmsMessage> =
+ s.messages.drain(..).filter(|m| m.date < oldest).collect();
+ let had_older = !older.is_empty();
+ s.messages = page;
+ s.messages.extend(older);
+ s.more = full || had_older && s.more;
+ } else {
+ s.messages.extend(page);
+ s.more = full;
+ }
+ s.messages
+ .iter()
+ .flat_map(|m| m.parts.iter())
+ .filter(|p| p.mime.starts_with("image/") && !s.pictures.contains_key(&p.id))
+ .map(|p| p.id.clone())
+ .collect()
+ }
+ Err(e) => {
+ tracing::debug!(error = %e, "can't read a conversation");
+ s.status = Status::of(&e);
+ Vec::new()
+ }
+ }
+ });
+ changed();
+ fetch_pictures(device, generation, wanted).await;
+ });
+}
+
+async fn fetch_pictures(device: DeviceId, generation: u64, parts: Vec<String>) {
+ let Some(node) = core_host::node() else { return };
+ let dir = files_dir();
+ for id in parts {
+ let Ok((mime, data)) = node.sms_part(device, id.clone()).await else { continue };
+ let ext = if mime.contains("png") {
+ "png"
+ } else if mime.contains("gif") {
+ "gif"
+ } else {
+ "jpg"
+ };
+ let path = dir
+ .join(format!("sms-part-{:016x}.{ext}", crate::photos::fingerprint(&format!("{device} {id}"))));
+ if std::fs::create_dir_all(&dir).and_then(|()| std::fs::write(&path, &data)).is_err() {
+ continue;
+ }
+ let current = state(|s| {
+ let current = s.generation == generation;
+ if current {
+ s.pictures.insert(id, path);
+ }
+ current
+ });
+ if !current {
+ return;
+ }
+ changed();
+ }
+}
+
+/// Why a text wasn't sent, for the page.
+pub fn send_problem(error: &Error) -> &'static str {
+ match error {
+ Error::Denied => "Messages are turned off for this phone.",
+ Error::Unsupported => {
+ "The phone doesn't send texts for this PC. Allow it in the Nectarlink app on the phone."
+ }
+ Error::Offline | Error::NotPaired | Error::Timeout => "The phone isn't connected.",
+ Error::TooLarge => "That's too long for a text.",
+ _ => "The phone couldn't send it.",
+ }
+}
+
+/// Sends a text in the open conversation.
+pub fn send(body: String) {
+ let to = state(|s| {
+ let thread = s.thread.as_ref()?;
+ s.threads.iter().find(|t| &t.id == thread).map(|t| t.addresses.clone())
+ });
+ match to {
+ Some(to) if to.len() == 1 => send_to(to, body),
+ Some(_) => crate::bridge::app::show_message("Group texts can't be sent from the PC yet."),
+ None => {}
+ }
+}
+
+/// Sends a text to a number (a new conversation), then opens it.
+pub fn send_to(to: Vec<String>, body: String) {
+ let Some(device) = state(|s| {
+ s.sending = true;
+ s.device
+ }) else {
+ return;
+ };
+ changed();
+ let Some(node) = core_host::node() else { return };
+ core_host::spawn(async move {
+ let result = node.sms_send(device, to.clone(), body).await;
+ state(|s| s.sending = false);
+ changed();
+ match result {
+ Ok(()) => {
+ // The phone also says so when it has stored it; this is sooner.
+ tokio::time::sleep(std::time::Duration::from_millis(600)).await;
+ reload_after_send(&to);
+ }
+ Err(e) => crate::bridge::app::show_message(send_problem(&e)),
+ }
+ });
+}
+
+fn reload_after_send(to: &[String]) {
+ let open = state(|s| s.thread.clone());
+ if open.is_none() {
+ // A new conversation: open it once the phone lists it.
+ let wanted: Vec<String> = to.iter().map(|a| digits(a)).collect();
+ PENDING_OPEN.lock().unwrap_or_else(|e| e.into_inner()).replace(wanted);
+ }
+ load_threads();
+ if open.is_some() {
+ load_messages(None);
+ }
+}
+
+/// A new conversation to open once it shows up, by its numbers' digits.
+static PENDING_OPEN: Mutex<Option<Vec<String>>> = Mutex::new(None);
+
+/// The last digits of a number, to match "+1 555-0100" with "5550100".
+fn digits(number: &str) -> String {
+ let all: String = number.chars().filter(char::is_ascii_digit).collect();
+ all[all.len().saturating_sub(9)..].to_owned()
+}
+
+/// Closes the open conversation (for writing a new one).
+pub fn close_thread() {
+ state(|s| {
+ s.thread = None;
+ s.messages.clear();
+ s.more = false;
+ });
+ changed();
+}
+
+pub fn on_event(event: &NodeEvent) {
+ let device = state(|s| s.device);
+ match event {
+ NodeEvent::SmsChanged { device: d, .. } if Some(*d) == device => {
+ load_threads();
+ if state(|s| s.thread.is_some()) {
+ load_messages(None);
+ }
+ }
+ NodeEvent::LinkChanged { device: d, link: LinkState::Online { .. } }
+ if Some(*d) == device && state(|s| s.status != Status::Ready) =>
+ {
+ load_threads();
+ }
+ NodeEvent::LinkChanged { device: d, link: LinkState::Offline { .. } } if Some(*d) == device => {
+ state(|s| s.status = Status::Offline);
+ changed();
+ }
+ _ => {}
+ }
+}
+
+/// Opens a conversation just started from the PC, once it's listed.
+fn open_pending() {
+ let Some(wanted) = PENDING_OPEN.lock().unwrap_or_else(|e| e.into_inner()).clone() else { return };
+ let found = state(|s| {
+ s.threads
+ .iter()
+ .find(|t| {
+ let have: Vec<String> = t.addresses.iter().map(|a| digits(a)).collect();
+ have == wanted
+ })
+ .map(|t| t.id.clone())
+ });
+ if let Some(thread) = found {
+ PENDING_OPEN.lock().unwrap_or_else(|e| e.into_inner()).take();
+ open_thread(thread);
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn thread(addresses: &[&str], names: &[&str]) -> SmsThread {
+ SmsThread {
+ id: "1".into(),
+ addresses: addresses.iter().map(|a| (*a).into()).collect(),
+ names: names.iter().map(|n| (*n).into()).collect(),
+ snippet: String::new(),
+ date: 0,
+ unread: 0,
+ photo: None,
+ }
+ }
+
+ #[test]
+ fn conversations_are_named_by_contact_or_number() {
+ assert_eq!(title_of(&thread(&["+1555"], &["Sam"])), "Sam");
+ assert_eq!(title_of(&thread(&["+1555", "+1666"], &["Sam", ""])), "Sam, +1666");
+ assert_eq!(title_of(&thread(&["+1555"], &[])), "+1555");
+ }
+
+ #[test]
+ fn numbers_match_however_they_are_written() {
+ assert_eq!(digits("+1 (555) 010-0100"), digits("5550100100"));
+ assert_eq!(digits("12"), "12");
+ }
+}
diff --git a/desktop/app/src/photos.rs b/desktop/app/src/photos.rs
index 23cd393..76dbff0 100644
--- a/desktop/app/src/photos.rs
+++ b/desktop/app/src/photos.rs
@@ -106,7 +106,12 @@ fn save_preview(device: DeviceId, photo: &Photo) -> Option<PathBuf> {
}
pub(crate) fn fingerprint(text: &str) -> u64 {
- text.bytes().fold(0xcbf2_9ce4_8422_2325, |hash, b| (hash ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3))
+ fingerprint_bytes(text.as_bytes())
+}
+
+/// FNV-1a: a stable name for cached files.
+pub(crate) fn fingerprint_bytes(bytes: &[u8]) -> u64 {
+ bytes.iter().fold(0xcbf2_9ce4_8422_2325, |hash, b| (hash ^ u64::from(*b)).wrapping_mul(0x0100_0000_01b3))
}
/// The user clicked the notification (`action` None) or one of its buttons.
diff --git a/desktop/app/src/state.rs b/desktop/app/src/state.rs
index 1b38d08..46bde58 100644
--- a/desktop/app/src/state.rs
+++ b/desktop/app/src/state.rs
@@ -36,6 +36,8 @@ impl Changes {
pub const APPS: Changes = Changes(1 << 10);
/// An update was found (see crate::updater).
pub const UPDATE: Changes = Changes(1 << 11);
+ /// A phone's text messages (kept by crate::messages).
+ pub const MESSAGES: Changes = Changes(1 << 12);
pub fn is_empty(self) -> bool {
self.0 == 0
@@ -380,11 +382,12 @@ impl AppState {
let gone = self.notifications.remove(at);
Changes::NOTIFICATIONS | self.remember(vec![gone])
}
- // Feedback (crate::clipboard) and notifications (crate::photos,
- // crate::calls) only; nothing to keep.
- NodeEvent::ClipboardReceived { .. } | NodeEvent::PhotoAdded { .. } | NodeEvent::Call { .. } => {
- Changes::NONE
- }
+ // Feedback (crate::clipboard), notifications (crate::photos,
+ // crate::calls) and state kept elsewhere (crate::messages).
+ NodeEvent::ClipboardReceived { .. }
+ | NodeEvent::PhotoAdded { .. }
+ | NodeEvent::Call { .. }
+ | NodeEvent::SmsChanged { .. } => Changes::NONE,
NodeEvent::Transfer(transfer) => self.update_transfer(transfer.clone(), Instant::now()),
// With artwork saved first (see crate::media).
NodeEvent::MediaChanged { .. } => Changes::NONE,
@@ -651,6 +654,11 @@ impl Hub {
}
}
+ /// Tells listeners about changes to state kept outside the hub.
+ pub fn changed(&self, changes: Changes) {
+ self.notify(changes);
+ }
+
fn notify(&self, changes: Changes) {
lock(&self.listeners).retain(|l| !l.interest.intersects(changes) || (l.notify)());
}
diff --git a/docs/protocol/capabilities.md b/docs/protocol/capabilities.md
index 4ad6807..8d350ab 100644
--- a/docs/protocol/capabilities.md
+++ b/docs/protocol/capabilities.md
@@ -34,8 +34,8 @@ capability is missing.
| `notify.mirror` | Forwards notifications ([notifications service](notifications.md)) | notification access |
| `notify.reply` | Accepts inline replies and actions on notifications | notification access |
| `notify.sensitive` | Forwards notifications Android hides as sensitive (e.g. one-time codes) | Elevated |
-| `sms.read` | Reads SMS conversations | SMS permission |
-| `sms.send` | Sends SMS | SMS permission |
+| `sms.read` | Lists conversations and messages ([messages](sms.md)) | SMS permission |
+| `sms.send` | Sends texts when a PC asks ([messages](sms.md)) | SMS permission |
| `call.state` | Reports incoming and ongoing calls ([calls](calls.md)) | phone permission |
| `call.control` | Answers, declines and silences calls when a PC asks ([calls](calls.md)) | phone permission |
| `clip.write` | Accepts clipboard content from the PC ([clipboard service](clipboard.md)) | app update |
@@ -56,6 +56,7 @@ capability is missing.
| `pc.power` | Locks or sleeps on request ([actions](actions.md)) | app update |
| `photos.show` | Shows a phone's new photos ([photos](photos.md)) | app update |
| `call.show` | Shows a phone's calls ([calls](calls.md)) | app update |
+| `sms.show` | Shows a phone's text messages ([messages](sms.md)) | app update |
| `files.browse` | Lets a paired phone browse and fetch its files | app update |
| `input.inject` | Accepts pointer and keyboard input (touchpad, air mouse, voice typing) | app update |
| `deck.actions` | Runs Deck actions | app update |
diff --git a/docs/protocol/sms.md b/docs/protocol/sms.md
new file mode 100644
index 0000000..e3adefb
--- /dev/null
+++ b/docs/protocol/sms.md
@@ -0,0 +1,97 @@
+# Messages service (protocol v0)
+
+> Status: **draft.** Builds on [protocol v0](v0.md); breaking changes are
+> allowed until v1. License: CC BY 4.0.
+
+A PC reads a phone's text messages (SMS and MMS) and sends texts through
+it. The phone keeps the messages; a PC asks for what it shows and keeps it
+only in memory. New-message alerts come from the phone's own notifications
+([notifications](notifications.md)), not from this service.
+
+## 1. Capabilities
+
+| ID | Offered by | Meaning |
+|---|---|---|
+| `sms.read` | phone | Lists conversations and messages (needs the SMS permission) |
+| `sms.send` | phone | Sends texts when a PC asks |
+| `sms.show` | PC | Shows messages, and wants `sms.changed` |
+
+Both devices must allow it: the `messages` device toggle, on by default,
+on each side.
+
+## 2. Messages
+
+On the control stream. Each request is answered with the matching answer
+or `error`.
+
+```
+t = "sms.threads" id = n b = { limit: uint } // 1–100
+t = "sms.threads" re = n b = { threads: [ thread ] } // newest first
+
+t = "sms.messages" id = n b = { thread: text, ? before: int, limit: uint }
+t = "sms.messages" re = n b = { messages: [ message ] } // newest first
+
+t = "sms.send" id = n b = { to: [ text ], body: text }
+t = "ok" re = n
+
+t = "sms.part" id = n b = { id: text }
+t = "sms.part" re = n b = { mime: text, data: bytes }
+
+t = "sms.changed" b = { ? thread: text } // phone → PC
+
+thread = {
+ id: text,
+ addresses: [ text ], // The other people's numbers; more than one is a group
+ ? names: [ text ], // Their contact names, in the same order ("" when not a contact)
+ ? snippet: text, // The latest message's text, or a description like "Picture"
+ date: int, // The latest message, in Unix milliseconds
+ ? unread: uint,
+ ? photo: bytes, // One-person conversations: the contact's photo, a JPEG of at most 16 KiB
+}
+
+message = {
+ id: text,
+ thread: text,
+ ? address: text, // Who sent it (received), or the recipient (sent)
+ ? body: text,
+ date: int, // Unix milliseconds
+ ? outgoing: bool, // Sent from the phone
+ ? status: "sent" | "pending" | "failed",
+ ? parts: [ { id: text, mime: text, ? size: uint } ], // Pictures and other attachments
+}
+```
+
+### 2.1 Reading
+
+`sms.messages` pages back through a conversation: `before` is the oldest
+`date` already shown. A phone answers with fewer items than `limit` when
+the answer wouldn't fit in a frame (v0 §3), dropping the oldest.
+
+`sms.part` fetches an attachment; parts larger than 900 KiB are refused
+with `BUSY`.
+
+### 2.2 Sending
+
+`sms.send` sends `body` (at most 8 KiB, not blank) to each of `to` (1–20
+numbers) as a text; the phone keeps it with the messages it sent. Errors:
+`DENIED` when messages are off for the PC, `UNSUPPORTED` when the phone
+doesn't offer `sms.send`, `INTERNAL` when it couldn't send.
+
+### 2.3 Changes
+
+The phone sends `sms.changed` to PCs that offer `sms.show` when its
+messages change (a text arrived or was sent), with the conversation when
+it knows it. PCs then ask again for what they show.
+
+## 3. Limits of this version
+
+- Texts are sent to one number at a time; replying in a group needs MMS
+ and isn't part of this version.
+- Phones can't mark messages as read for other apps: Android lets only the
+ default SMS app change the messages store.
+- Android 15 and later keep texts with one-time codes from other apps for
+ a few hours; such conversations look empty in the meantime.
+
+## 4. Privacy
+
+Numbers, names, text and pictures are never logged (v0 §11).