forked from upstream-mirrors/quik
Fix duplicate Matrix forwarding, contact names and bridge reset
Build and Release APK / Build APK (push) Successful in 12m11s
Build and Release APK / Build APK (push) Successful in 12m11s
This commit is contained in:
@@ -15,11 +15,7 @@
|
||||
<uses-permission android:name="android.permission.SEND_SMS" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_REMOTE_MESSAGING" />
|
||||
<application>
|
||||
<receiver android:name="ch.skew.remotrix.receiver.OnSMS" android:exported="true" android:permission="android.permission.BROADCAST_SMS">
|
||||
<intent-filter>
|
||||
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
|
||||
</intent-filter>
|
||||
</receiver>
|
||||
<!-- Incoming SMS are forwarded after Quik persists them in MessageRepositoryImpl. -->
|
||||
<receiver android:name="ch.skew.remotrix.receiver.OnBoot" android:exported="true" android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.BOOT_COMPLETED"/>
|
||||
|
||||
@@ -38,6 +38,7 @@ import ch.skew.remotrix.data.RemotrixDB
|
||||
import ch.skew.remotrix.data.RemotrixSettings
|
||||
import io.ktor.http.Url
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.flow.first
|
||||
import net.folivo.trixnity.clientserverapi.client.SyncState
|
||||
import kotlinx.coroutines.launch
|
||||
@@ -246,6 +247,7 @@ fun onLoginClick(
|
||||
val localPart =
|
||||
Regex("@([a-z0-9_.-]+):").find(username.lowercase())?.value ?: username.lowercase()
|
||||
scope.launch {
|
||||
var clientToClose: MatrixClient? = null
|
||||
try {
|
||||
android.util.Log.d("RemotrixLogin", "onLoginClick started for user=$username, url=$baseUrl")
|
||||
update(VerificationStep.STARTED)
|
||||
@@ -275,6 +277,7 @@ fun onLoginClick(
|
||||
abort(it.message ?: context.getString(R.string.generic_error))
|
||||
return@launch
|
||||
}
|
||||
clientToClose = client
|
||||
android.util.Log.d("RemotrixLogin", "loginWithPassword succeeded! userId=${client.userId}")
|
||||
// The "via" part of m.space.child/parent event.
|
||||
val via = setOf(client.userId.domain)
|
||||
@@ -418,6 +421,12 @@ fun onLoginClick(
|
||||
if (settings.getDefaultForwarder.first() == -1) {
|
||||
settings.saveDefaultForwarder(id.toInt())
|
||||
}
|
||||
// The service opens its own client. Release this setup client first,
|
||||
// so reset/reload can close and delete each encryption store safely.
|
||||
(client as CoroutineScope).cancel()
|
||||
client.coroutineContext[Job]?.join()
|
||||
client.di.get<TrixnityRoomDatabase>().close()
|
||||
clientToClose = null
|
||||
Intent(context, CommandService::class.java)
|
||||
.apply {
|
||||
action = CommandService.RELOAD
|
||||
@@ -427,6 +436,14 @@ fun onLoginClick(
|
||||
} catch (e: Throwable) {
|
||||
android.util.Log.e("RemotrixLogin", "onLoginClick exception: ${e.message}", e)
|
||||
abort(e.message ?: e.toString())
|
||||
} finally {
|
||||
clientToClose?.let { client ->
|
||||
kotlinx.coroutines.withContext(kotlinx.coroutines.NonCancellable) {
|
||||
(client as CoroutineScope).cancel()
|
||||
client.coroutineContext[Job]?.join()
|
||||
client.di.get<TrixnityRoomDatabase>().close()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,13 +3,11 @@ package ch.skew.remotrix.background
|
||||
import android.app.Service
|
||||
import android.content.Intent
|
||||
import android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_REMOTE_MESSAGING
|
||||
import android.net.Uri
|
||||
import android.os.ResultReceiver
|
||||
import android.os.IBinder
|
||||
import android.provider.ContactsContract
|
||||
import android.telephony.SmsManager
|
||||
import android.util.Log
|
||||
import androidx.core.app.NotificationCompat
|
||||
import androidx.core.net.toUri
|
||||
import androidx.room.Room.databaseBuilder
|
||||
import ch.skew.remotrix.R
|
||||
import ch.skew.remotrix.classes.Account
|
||||
@@ -22,16 +20,23 @@ import ch.skew.remotrix.data.RemotrixDB
|
||||
import ch.skew.remotrix.data.RemotrixSettings
|
||||
import ch.skew.remotrix.data.forwardRuleDB.ForwardRule
|
||||
import ch.skew.remotrix.data.roomIdDB.RoomIdData
|
||||
import ch.skew.remotrix.bridge.resetBridge
|
||||
import ch.skew.remotrix.bridge.RoomResolver
|
||||
import ch.skew.remotrix.contacts.ContactLookup
|
||||
import io.ktor.http.ContentDisposition
|
||||
import io.ktor.http.ContentType
|
||||
import io.ktor.utils.io.ByteReadChannel
|
||||
import kotlinx.coroutines.CoroutineExceptionHandler
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.cancel
|
||||
import kotlinx.coroutines.withTimeoutOrNull
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.first
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
import kotlinx.coroutines.withContext
|
||||
import net.folivo.trixnity.client.MatrixClient
|
||||
import net.folivo.trixnity.client.fromStore
|
||||
@@ -52,6 +57,7 @@ import net.folivo.trixnity.clientserverapi.model.media.Media
|
||||
import net.folivo.trixnity.core.model.RoomId
|
||||
import net.folivo.trixnity.core.model.UserId
|
||||
import net.folivo.trixnity.core.model.events.InitialStateEvent
|
||||
import net.folivo.trixnity.core.model.events.m.room.NameEventContent
|
||||
import net.folivo.trixnity.core.model.events.m.room.AvatarEventContent
|
||||
import net.folivo.trixnity.core.model.events.m.room.EncryptionEventContent
|
||||
import net.folivo.trixnity.core.model.events.m.room.HistoryVisibilityEventContent
|
||||
@@ -72,7 +78,7 @@ enum class StatusType {
|
||||
}
|
||||
|
||||
class CurrentStatus(
|
||||
private var status: StatusType = StatusType.NotStarted,
|
||||
@Volatile private var status: StatusType = StatusType.NotStarted,
|
||||
private val lock: Mutex = Mutex()
|
||||
) {
|
||||
fun get() = status
|
||||
@@ -102,6 +108,11 @@ class CommandService: Service() {
|
||||
private lateinit var settings: RemotrixSettings
|
||||
private lateinit var db: RemotrixDB
|
||||
private var currentStatus = CurrentStatus()
|
||||
private val loadMutex = Mutex()
|
||||
private val roomResolver = RoomResolver(
|
||||
lookup = { number, account -> db.getRoomIdDao().getDestRoom(number, account) },
|
||||
save = { number, account, room -> db.getRoomIdDao().insert(RoomIdData(number, account, room)); Unit }
|
||||
)
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
@@ -122,6 +133,18 @@ class CommandService: Service() {
|
||||
}
|
||||
}
|
||||
when(intent?.action) {
|
||||
RESET_MATRIX -> {
|
||||
val receiver = intent.getParcelableExtra<ResultReceiver>(RESET_RESULT_RECEIVER)
|
||||
CoroutineScope(Dispatchers.IO).launch {
|
||||
try {
|
||||
resetMatrix()
|
||||
receiver?.send(RESET_SUCCESS, null)
|
||||
} catch (error: Exception) {
|
||||
Log.e("CommandService", "Matrix reset failed", error)
|
||||
receiver?.send(RESET_FAILURE, null)
|
||||
}
|
||||
}
|
||||
}
|
||||
INVITE -> {
|
||||
CoroutineScope(Dispatchers.IO).launch(exceptionHandler) {
|
||||
val id = intent.getIntExtra(ACCOUNT_ID, -1)
|
||||
@@ -148,7 +171,7 @@ class CommandService: Service() {
|
||||
// Payload should be there too
|
||||
// TODO
|
||||
} else {
|
||||
CoroutineScope(Dispatchers.IO).launch(exceptionHandler) {
|
||||
scope.launch(exceptionHandler) {
|
||||
val log = settings.getLogging.first()
|
||||
sendMsg(sender, payload, log, outgoing)
|
||||
}
|
||||
@@ -172,6 +195,34 @@ class CommandService: Service() {
|
||||
return super.onStartCommand(intent, flags, startId)
|
||||
}
|
||||
|
||||
private suspend fun resetMatrix() = loadMutex.withLock {
|
||||
currentStatus.set(StatusType.ShuttingDown)
|
||||
val accountIds = db.getAccountDao().getAccountIds()
|
||||
resetBridge(scope,
|
||||
stopClients = {
|
||||
for ((client, _) in clients.values) {
|
||||
withTimeoutOrNull(10_000) { client.stopSync() }
|
||||
(client as CoroutineScope).cancel()
|
||||
client.coroutineContext[Job]?.join()
|
||||
client.di.get<TrixnityRoomDatabase>().close()
|
||||
}
|
||||
clients.clear()
|
||||
},
|
||||
clearData = {
|
||||
for (id in accountIds) applicationContext.deleteDatabase("ClientData_$id")
|
||||
applicationContext.filesDir.resolve("clients").deleteRecursively()
|
||||
// This database contains only Matrix accounts, mappings, rules and logs.
|
||||
// SMS and Quik preferences live in separate stores.
|
||||
db.clearAllTables()
|
||||
settings.resetConnection()
|
||||
}
|
||||
)
|
||||
currentStatus.set(StatusType.NotStarted)
|
||||
scope = CoroutineScope(Dispatchers.IO)
|
||||
stopForeground(STOP_FOREGROUND_REMOVE)
|
||||
stopSelf()
|
||||
}
|
||||
|
||||
private suspend fun inviteManager(id: Int) {
|
||||
if(currentStatus.get() != StatusType.Running) {
|
||||
startAll()
|
||||
@@ -251,31 +302,10 @@ class CommandService: Service() {
|
||||
|
||||
private suspend fun createRoom(client: MatrixClient, account: Account, sender: PhoneNumber, encrypted: Boolean = true): Result<RoomId> {
|
||||
// The "via" part of m.space.child/parent event.
|
||||
var picUri: Uri? = null
|
||||
val via = setOf(client.userId.domain)
|
||||
var roomName = sender.number
|
||||
val contacts = applicationContext.contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null)
|
||||
if (contacts !== null) {
|
||||
while (contacts.moveToNext()){
|
||||
val numberIndex = contacts.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)
|
||||
if (numberIndex < 0) continue
|
||||
val current = contacts.getString(numberIndex).filter { it.isDigit() }
|
||||
if(current == sender.number) {
|
||||
val nameIndex = contacts.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)
|
||||
val pictureIndex = contacts.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_URI)
|
||||
if(pictureIndex >= 0) {
|
||||
val uri = contacts.getString(pictureIndex)
|
||||
if (uri !== null) picUri = uri.toUri()
|
||||
}
|
||||
if(nameIndex >= 0){
|
||||
val name = contacts.getString(nameIndex)
|
||||
if (name !== null) roomName = name
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
contacts.close()
|
||||
}
|
||||
val contact = ContactLookup(applicationContext).find(sender.number)
|
||||
val roomName = contact?.name ?: sender.number
|
||||
val picUri = contact?.photo
|
||||
val initialStates = mutableListOf(
|
||||
// Initial event for making this room child of the message room
|
||||
InitialStateEvent(
|
||||
@@ -322,7 +352,7 @@ class CommandService: Service() {
|
||||
ByteReadChannel(stream.readBytes()),
|
||||
contentLength = length.toLong(),
|
||||
contentType = ContentType("image", "jpeg"),
|
||||
contentDisposition = TODO()
|
||||
contentDisposition = ContentDisposition.Inline
|
||||
)
|
||||
).fold(
|
||||
{
|
||||
@@ -411,35 +441,24 @@ class CommandService: Service() {
|
||||
while (client.syncState.first() != net.folivo.trixnity.clientserverapi.client.SyncState.RUNNING) {
|
||||
kotlinx.coroutines.delay(1000)
|
||||
}
|
||||
val sendTo = db.getRoomIdDao().getDestRoom(sender, sendAs)
|
||||
val managerId = settings.getManagerId.first()
|
||||
// If an appropriate room does not exist for a given forwarder-SMS sender is not found, a new room is created.
|
||||
val roomId = if (sendTo === null) {
|
||||
val number = PhoneNumber.from(sender).getOrElse {
|
||||
if (currentLog != -1L) db.getLogDao().setFailure(
|
||||
currentLog,
|
||||
if (it is RoomCreationError) it.error else MsgStatus.CANNOT_CREATE_ROOM,
|
||||
null,
|
||||
null
|
||||
)
|
||||
return
|
||||
}
|
||||
this.createRoom(client, pair.second, number).getOrElse {
|
||||
if (currentLog != -1L) db.getLogDao().setFailure(
|
||||
currentLog,
|
||||
if (it is RoomCreationError) it.error else MsgStatus.CANNOT_CREATE_ROOM,
|
||||
null,
|
||||
null
|
||||
)
|
||||
return
|
||||
}
|
||||
} else RoomId(sendTo)
|
||||
// If this was null, it means that this entry was not present in the database. It is entered here.
|
||||
if (sendTo === null) {
|
||||
val resolved = roomResolver.resolve(sender, sendAs) {
|
||||
val number = PhoneNumber.from(sender).getOrElse { return@resolve Result.failure(it) }
|
||||
createRoom(client, pair.second, number).map { it.full }
|
||||
}.getOrElse {
|
||||
if (currentLog != -1L) db.getLogDao().setFailure(
|
||||
currentLog,
|
||||
if (it is RoomCreationError) it.error else MsgStatus.CANNOT_CREATE_ROOM,
|
||||
null,
|
||||
null
|
||||
)
|
||||
return
|
||||
}
|
||||
val roomId = RoomId(resolved.roomId)
|
||||
if (resolved.created) {
|
||||
client.room.sendMessage(roomId) {
|
||||
text(getString(R.string.startup_1).format(client.userId.full, client.deviceId, sender))
|
||||
}
|
||||
db.getRoomIdDao().insert(RoomIdData(sender, sendAs, roomId.full))
|
||||
val managerId = settings.getManagerId.first()
|
||||
if (managerId.isNotBlank()) {
|
||||
client.api.room.inviteUser(roomId, UserId(managerId))
|
||||
}
|
||||
@@ -477,8 +496,8 @@ class CommandService: Service() {
|
||||
}
|
||||
else if(currentStatus.get() == StatusType.NotStarted) load()
|
||||
}
|
||||
private suspend fun load() {
|
||||
if (!currentStatus.compareAndSet(StatusType.NotStarted, StatusType.Loading)) return
|
||||
private suspend fun load(): Unit = loadMutex.withLock {
|
||||
if (!currentStatus.compareAndSet(StatusType.NotStarted, StatusType.Loading)) return@withLock
|
||||
clients.clear()
|
||||
val accounts = Account.from(db.getAccountDao().getAllAccounts().first())
|
||||
for(a in accounts){
|
||||
@@ -517,25 +536,18 @@ class CommandService: Service() {
|
||||
}
|
||||
|
||||
// Start up client
|
||||
CoroutineScope(Dispatchers.IO).launch(exceptionHandler) {
|
||||
scope.launch(exceptionHandler) {
|
||||
clients.forEach {
|
||||
val client = it.value.first
|
||||
while(!client.initialSyncDone.first()) delay(1000)
|
||||
scope.launch(exceptionHandler) {
|
||||
refreshContactNames(client, it.value.second.id)
|
||||
}
|
||||
if (settings.getEnableOnBootMessage.first()){
|
||||
client.room.sendMessage(RoomId(it.value.second.managementRoom)) {
|
||||
text(getString(R.string.ready_to_accept_commands).format(client.userId.full))
|
||||
}
|
||||
}
|
||||
if (!settings.getBackfillDone.first()) {
|
||||
CoroutineScope(Dispatchers.IO).launch {
|
||||
try {
|
||||
performBackfill(it.value.second.id, client, settings.getBackfillLimit.first())
|
||||
settings.saveBackfillDone(true)
|
||||
} catch (e: Exception) {
|
||||
Log.e("CommandService", "Backfill failed", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
scope.launch {
|
||||
client.room.getTimelineEventsFromNowOn(decryptionTimeout = 10.seconds).collect { ev ->
|
||||
if(ev.event.sender.full == client.userId.full) return@collect
|
||||
@@ -573,6 +585,12 @@ class CommandService: Service() {
|
||||
}
|
||||
}
|
||||
}
|
||||
// Backfill already routes each message to its selected account in sendMsg.
|
||||
// Running it for every client duplicates the entire history.
|
||||
if (clients.isNotEmpty() && !settings.getBackfillDone.first()) {
|
||||
performBackfill(settings.getBackfillLimit.first())
|
||||
settings.saveBackfillDone(true)
|
||||
}
|
||||
}
|
||||
if(clients.isNotEmpty()){
|
||||
currentStatus.set(StatusType.Running)
|
||||
@@ -632,21 +650,21 @@ class CommandService: Service() {
|
||||
val number = PhoneNumber.from(args[1]).getOrElse {
|
||||
return CommandAction.Reply(getString(R.string.error_invalid_phone_number))
|
||||
}
|
||||
db.getRoomIdDao().getDestRoom(number.number, account.second.id)?.let {
|
||||
client.api.room.inviteUser(RoomId(it), event.event.sender)
|
||||
return CommandAction.Reply(getString(R.string.room_already_exists))
|
||||
val resolved = roomResolver.resolve(number.number, account.second.id) {
|
||||
createRoom(client, account.second, number).map { it.full }
|
||||
}.getOrElse {
|
||||
return CommandAction.Reply(getString(R.string.error_cannot_create_messaging_room))
|
||||
}
|
||||
val roomId = this.createRoom(client, account.second, number).getOrNull()
|
||||
return if (roomId !== null) {
|
||||
client.api.room.inviteUser(roomId, event.event.sender)
|
||||
val roomId = RoomId(resolved.roomId)
|
||||
client.api.room.inviteUser(roomId, event.event.sender)
|
||||
if (resolved.created) {
|
||||
client.room.sendMessage(roomId) {
|
||||
text(getString(R.string.startup_1).format(client.userId.full, client.deviceId, args[1]))
|
||||
text(getString(R.string.startup_1).format(client.userId.full, client.deviceId, number.number))
|
||||
}
|
||||
db.getRoomIdDao().insert(RoomIdData(args[1], account.second.id, roomId.full))
|
||||
CommandAction.Reply(getString(R.string.room_created))
|
||||
} else {
|
||||
CommandAction.Reply(getString(R.string.error_cannot_create_messaging_room))
|
||||
}
|
||||
return CommandAction.Reply(getString(
|
||||
if (resolved.created) R.string.room_created else R.string.room_already_exists
|
||||
))
|
||||
|
||||
} else return CommandAction.Reply(getString(R.string.unknown_command))
|
||||
} else if(event.roomId.full != account.second.managementRoom) {
|
||||
@@ -672,10 +690,16 @@ class CommandService: Service() {
|
||||
return null
|
||||
}
|
||||
|
||||
private suspend fun performBackfill(accountId: Int, client: MatrixClient, limit: Int) {
|
||||
while (client.syncState.first() != net.folivo.trixnity.clientserverapi.client.SyncState.RUNNING) {
|
||||
kotlinx.coroutines.delay(1000)
|
||||
private suspend fun refreshContactNames(client: MatrixClient, accountId: Int) {
|
||||
val lookup = ContactLookup(applicationContext)
|
||||
for (room in db.getRoomIdDao().getRooms(accountId)) {
|
||||
val name = lookup.find(room.phoneNumber)?.name ?: continue
|
||||
client.api.room.sendStateEvent(RoomId(room.roomId), NameEventContent(name), "")
|
||||
.onFailure { Log.w("CommandService", "Could not update contact room name", it) }
|
||||
}
|
||||
}
|
||||
|
||||
private suspend fun performBackfill(limit: Int) {
|
||||
val bridge = ch.skew.remotrix.bridge.MatrixBridgeProvider.bridge ?: return
|
||||
val messagesToSend = bridge.getBackfillMessages(limit)
|
||||
Log.d("CommandService", "Starting backfill with ${messagesToSend.size} messages")
|
||||
@@ -720,6 +744,10 @@ class CommandService: Service() {
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val RESET_MATRIX = "RESET_MATRIX"
|
||||
const val RESET_RESULT_RECEIVER = "RESET_RESULT_RECEIVER"
|
||||
const val RESET_SUCCESS = 0
|
||||
const val RESET_FAILURE = 1
|
||||
const val START_ALL = "START_ALL"
|
||||
const val STOP_ALL = "STOP_ALL"
|
||||
const val SEND_MSG = "SEND_MSG"
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
package ch.skew.remotrix.bridge
|
||||
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.cancelAndJoin
|
||||
|
||||
/** Do not delete mappings or encryption stores while forwarding jobs can still use them. */
|
||||
suspend fun resetBridge(
|
||||
work: CoroutineScope,
|
||||
stopClients: suspend () -> Unit,
|
||||
clearData: suspend () -> Unit
|
||||
) {
|
||||
work.coroutineContext[Job]?.cancelAndJoin()
|
||||
stopClients()
|
||||
clearData()
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package ch.skew.remotrix.bridge
|
||||
|
||||
import kotlinx.coroutines.sync.Mutex
|
||||
import kotlinx.coroutines.sync.withLock
|
||||
|
||||
/** Shares one critical section between incoming messages, backfill and !new commands. */
|
||||
class RoomResolver(
|
||||
private val lookup: suspend (String, Int) -> String?,
|
||||
private val save: suspend (String, Int, String) -> Unit
|
||||
) {
|
||||
data class Resolution(val roomId: String, val created: Boolean)
|
||||
private val mutex = Mutex()
|
||||
|
||||
suspend fun resolve(
|
||||
number: String,
|
||||
account: Int,
|
||||
create: suspend () -> Result<String>
|
||||
): Result<Resolution> = mutex.withLock {
|
||||
val existing = lookup(number, account)
|
||||
if (existing != null) return@withLock Result.success(Resolution(existing, false))
|
||||
create().map { roomId ->
|
||||
// Persist before releasing the lock or sending any startup messages.
|
||||
save(number, account, roomId)
|
||||
Resolution(roomId, true)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package ch.skew.remotrix.contacts
|
||||
|
||||
import android.content.Context
|
||||
import android.net.Uri
|
||||
import android.provider.ContactsContract.PhoneLookup
|
||||
|
||||
/** Uses Android's country-aware phone matching instead of comparing raw contact numbers. */
|
||||
class ContactLookup(private val context: Context) {
|
||||
data class Contact(val name: String?, val photo: Uri?)
|
||||
|
||||
fun find(number: String): Contact? {
|
||||
val uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number))
|
||||
return try {
|
||||
context.contentResolver.query(
|
||||
uri, arrayOf(PhoneLookup.DISPLAY_NAME, PhoneLookup.PHOTO_URI), null, null, null
|
||||
)?.use { cursor ->
|
||||
if (!cursor.moveToFirst()) return@use null
|
||||
Contact(
|
||||
cursor.getString(0)?.takeIf { it.isNotBlank() },
|
||||
cursor.getString(1)?.takeIf { it.isNotBlank() }?.let(Uri::parse)
|
||||
)
|
||||
}
|
||||
} catch (_: SecurityException) {
|
||||
// SMS forwarding must also work when contact permission is denied.
|
||||
null
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -159,6 +159,14 @@ class RemotrixSettings(
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun resetConnection() {
|
||||
context.dataStore.edit { preferences ->
|
||||
preferences.remove(defaultForwarder)
|
||||
preferences.remove(managementSpaceId)
|
||||
preferences.remove(backfillDone)
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun saveBackfillDone(set: Boolean) {
|
||||
context.dataStore.edit { preferences ->
|
||||
preferences[backfillDone] = if (set) "1" else "0"
|
||||
|
||||
@@ -10,6 +10,8 @@ interface AccountDao{
|
||||
suspend fun insert(userId: String, baseUrl: String): Long
|
||||
@Query("SELECT message_space FROM accounts WHERE id = :id")
|
||||
suspend fun getMessageSpace(id: Int): String
|
||||
@Query("SELECT id FROM accounts")
|
||||
suspend fun getAccountIds(): List<Int>
|
||||
@Query("DELETE FROM accounts WHERE id = :id")
|
||||
suspend fun delete(id: Int): Int
|
||||
@Query("SELECT * FROM accounts WHERE domain NOT NULL")
|
||||
|
||||
@@ -13,6 +13,9 @@ interface RoomIdDao{
|
||||
@Query("SELECT room_id FROM room_ids WHERE phone_number = :phoneNumber AND forwarder_id = :forwarderId")
|
||||
suspend fun getDestRoom(phoneNumber: String, forwarderId: Int): String?
|
||||
|
||||
@Query("SELECT * FROM room_ids WHERE forwarder_id = :forwarderId")
|
||||
suspend fun getRooms(forwarderId: Int): List<RoomIdData>
|
||||
|
||||
/// Given a room ID, get the corresponding phone number
|
||||
@Query("SELECT phone_number FROM room_ids WHERE room_id = :roomId AND forwarder_id = :forwarderId")
|
||||
suspend fun getPhoneNumber(roomId: String, forwarderId: Int): String?
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
package ch.skew.remotrix.bridge
|
||||
|
||||
import kotlinx.coroutines.CompletableDeferred
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.NonCancellable
|
||||
import kotlinx.coroutines.awaitCancellation
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import kotlinx.coroutines.withContext
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
class BridgeResetTest {
|
||||
@Test
|
||||
fun waitsForInFlightForwardingBeforeDeletingMappings() = runBlocking {
|
||||
val work = CoroutineScope(Job() + Dispatchers.Default)
|
||||
val started = CompletableDeferred<Unit>()
|
||||
val mappings = mutableListOf<String>()
|
||||
var clientsStopped = false
|
||||
work.launch {
|
||||
try {
|
||||
started.complete(Unit)
|
||||
awaitCancellation()
|
||||
} finally {
|
||||
// A forwarding job may still persist its result during cleanup.
|
||||
withContext(NonCancellable) {
|
||||
delay(20)
|
||||
mappings.add("old room")
|
||||
}
|
||||
}
|
||||
}
|
||||
started.await()
|
||||
resetBridge(work,
|
||||
stopClients = { clientsStopped = true },
|
||||
clearData = {
|
||||
assertTrue(clientsStopped)
|
||||
assertEquals(listOf("old room"), mappings)
|
||||
mappings.clear()
|
||||
}
|
||||
)
|
||||
assertTrue(mappings.isEmpty())
|
||||
assertFalse(work.coroutineContext[Job]!!.isActive)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun doesNotDeleteStoresWhenStoppingClientsFails() = runBlocking {
|
||||
val work = CoroutineScope(Job())
|
||||
var deleted = false
|
||||
val result = runCatching {
|
||||
resetBridge(work,
|
||||
stopClients = { error("store is still open") },
|
||||
clearData = { deleted = true }
|
||||
)
|
||||
}
|
||||
assertTrue(result.isFailure)
|
||||
assertFalse(deleted)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package ch.skew.remotrix.bridge
|
||||
|
||||
import kotlinx.coroutines.async
|
||||
import kotlinx.coroutines.awaitAll
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
class RoomResolverTest {
|
||||
@Test
|
||||
fun concurrentMessagesAndCommandsCreateOneRoom() = runBlocking {
|
||||
val mappings = mutableMapOf<Pair<String, Int>, String>()
|
||||
var creations = 0
|
||||
val resolver = RoomResolver(
|
||||
lookup = { number, account -> mappings[number to account] },
|
||||
save = { number, account, room -> mappings[number to account] = room }
|
||||
)
|
||||
val results = (1..20).map {
|
||||
async {
|
||||
resolver.resolve("+48123456789", 1) {
|
||||
creations++
|
||||
delay(10) // Room creation suspends while other requests arrive.
|
||||
Result.success("!room:example.org")
|
||||
}.getOrThrow()
|
||||
}
|
||||
}.awaitAll()
|
||||
assertEquals(1, creations)
|
||||
assertEquals(1, results.count { it.created })
|
||||
assertTrue(results.all { it.roomId == "!room:example.org" })
|
||||
}
|
||||
|
||||
@Test
|
||||
fun failedCreationCanBeRetriedAndAccountsStaySeparate() = runBlocking {
|
||||
val mappings = mutableMapOf<Pair<String, Int>, String>()
|
||||
val resolver = RoomResolver(
|
||||
lookup = { number, account -> mappings[number to account] },
|
||||
save = { number, account, room -> mappings[number to account] = room }
|
||||
)
|
||||
assertTrue(resolver.resolve("123", 1) {
|
||||
Result.failure(IllegalStateException("offline"))
|
||||
}.isFailure)
|
||||
assertTrue(mappings.isEmpty())
|
||||
assertEquals("!one:example.org", resolver.resolve("123", 1) {
|
||||
Result.success("!one:example.org")
|
||||
}.getOrThrow().roomId)
|
||||
assertEquals("!two:example.org", resolver.resolve("123", 2) {
|
||||
Result.success("!two:example.org")
|
||||
}.getOrThrow().roomId)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user