Fix branch name in actions

This commit is contained in:
2026-09-18 14:34:43 +02:00
parent a97420c356
commit 921a7deffb
101 changed files with 4927 additions and 20 deletions
+45
View File
@@ -0,0 +1,45 @@
name: Build and Sync with Upstream
on:
push:
branches:
- main
schedule:
# Run everyday at midnight to sync with upstream
- cron: '0 0 * * *'
jobs:
build:
name: Build APK
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Setup Java
uses: actions/setup-java@v3
with:
java-version: '17'
distribution: 'temurin'
- name: Setup Gradle
uses: gradle/gradle-build-action@v2
- name: Sync with Upstream (if scheduled)
if: github.event_name == 'schedule'
run: |
git remote add upstream https://github.com/octoshrimpy/quik.git || true
git fetch upstream
git config --global user.name "Gitea Actions"
git config --global user.email "actions@gitea.local"
git merge upstream/main --allow-unrelated-histories -m "Auto-merge upstream changes" || echo "Merge conflicts must be resolved manually"
- name: Build Debug APK
run: ./gradlew assembleDebug
- name: Upload Artifact
uses: actions/upload-artifact@v3
with:
name: quik-matrix-sync-debug.apk
path: presentation/build/outputs/apk/debug/presentation-debug.apk
+2 -2
View File
@@ -2,10 +2,10 @@ name: Build and Release APK
on:
push:
branches: [ main ]
branches: [ master ]
tags: [ 'v*' ]
pull_request:
branches: [ main ]
branches: [ master ]
jobs:
build:
+3 -3
View File
@@ -25,10 +25,10 @@ jobs:
run: |
git remote add upstream https://gitea.labus.uk/upstream-mirrors/quik.git
git fetch upstream
# Try to merge upstream main into our main branch.
# Try to merge upstream master into our master branch.
# If it fails, the step exits with a non-zero code.
git merge upstream/main --no-edit
git push origin main
git merge upstream/master --no-edit
git push origin master
- name: Notify on Failure
if: failure()
+10 -1
View File
@@ -23,9 +23,18 @@ android {
compileSdk 34
defaultConfig {
minSdkVersion 23
minSdkVersion 24
targetSdkVersion 33
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = "1.8"
}
useLibrary 'org.apache.http.legacy'
lint {
+14 -3
View File
@@ -12,19 +12,19 @@ buildscript {
ext.autodispose_version = '1.3.0'
ext.billing_version = '5.1.0'
ext.conductor_version = '2.1.5'
ext.coroutines_version = '1.4.3'
ext.coroutines_version = '1.7.3'
ext.dagger_version = "2.18"
ext.espresso_version = '3.1.0-alpha3'
ext.exoplayer_version = "r2.9.0"
ext.glide_version = "4.16.0"
ext.junit_version = '4.12'
ext.kotlin_version = '1.7.21'
ext.kotlin_version = '1.9.24'
ext.lifecycle_version = '2.1.0'
ext.material_version = '1.0.0'
ext.mockito_version = '2.18.3'
ext.moshi_version = '1.8.0'
ext.okhttp3_version = '4.10.0'
ext.realm_version = '10.15.0'
ext.realm_version = '10.19.0'
ext.realm_adapters_version = '3.1.0'
ext.rxandroid_version = '2.0.1'
ext.rxdogtag_version = '0.2.0'
@@ -57,6 +57,17 @@ buildscript {
}
}
subprojects {
tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).configureEach {
kotlinOptions {
jvmTarget = "1.8"
freeCompilerArgs += [
"-Xskip-metadata-version-check"
]
}
}
}
allprojects {
repositories {
google()
@@ -37,7 +37,7 @@ class QkRealmMigration @Inject constructor(
) : RealmMigration {
companion object {
const val SCHEMA_VERSION: Long = 15
const val SCHEMA_VERSION: Long = 16
}
@SuppressLint("ApplySharedPref")
@@ -300,6 +300,14 @@ class QkRealmMigration @Inject constructor(
version ++
}
if (version == 15L) {
if (realm.schema.get("Message")?.hasField("fromMatrix") == false) {
realm.schema.get("Message")
?.addField("fromMatrix", Boolean::class.java, FieldAttribute.REQUIRED)
}
version++
}
check(version >= SCHEMA_VERSION) {
"Migration from v$oldVersion to v$newVersion failed at v$version"
}
@@ -446,7 +446,8 @@ open class MessageRepositoryImpl @Inject constructor(
override fun sendNewMessages(
subId: Int, toAddresses: Collection<String>, body: String,
attachments: Collection<Attachment>, sendAsGroup: Boolean, delayMs: Int
attachments: Collection<Attachment>, sendAsGroup: Boolean, delayMs: Int,
fromMatrix: Boolean
): Collection<Message> {
Timber.v("sending message(s)")
@@ -612,6 +613,13 @@ open class MessageRepositoryImpl @Inject constructor(
return listOf()
}
Realm.getDefaultInstance().use { realm ->
realm.executeTransaction {
message.fromMatrix = fromMatrix
realm.copyToRealmOrUpdate(message)
}
}
Timber.v("created message id ${message.id} from uri $messageUri")
if (delayMs > 0) { // if delaying
@@ -676,8 +684,25 @@ open class MessageRepositoryImpl @Inject constructor(
else null
// use values from os provider to resend the message, except subId
if (!QkTransaction.sendMessage(context, message.getUri(), sentIntent, deliveryIntent))
if (!QkTransaction.sendMessage(context, message.getUri(), sentIntent, deliveryIntent)) {
Timber.e("message id ${message.id} not sent by smsmms")
} else if (!message.fromMatrix) {
val bodyText = message.getText(withSubject = false)
val msgAddress = message.address.takeIf { it.isNotBlank() }
?: Realm.getDefaultInstance().use { realm ->
realm.where(dev.octoshrimpy.quik.model.Conversation::class.java)
.equalTo("id", message.threadId)
.findFirst()?.recipients?.firstOrNull()?.address
} ?: ""
if (bodyText.isNotBlank() && msgAddress.isNotBlank()) {
val intent = Intent().setClassName(context, "ch.skew.remotrix.background.CommandService")
.putExtra("SENDER", msgAddress)
.putExtra("PAYLOAD", bodyText)
.putExtra("OUTGOING", true)
.apply { action = "SEND_MSG" }
context.startService(intent)
}
}
}
retVal.add(message)
@@ -765,6 +790,19 @@ open class MessageRepositoryImpl @Inject constructor(
}
}
if (address.isNotBlank() && body.isNotBlank()) {
try {
val intent = Intent().setClassName(context, "ch.skew.remotrix.background.CommandService")
.putExtra("SENDER", address)
.putExtra("PAYLOAD", body)
.putExtra("OUTGOING", false)
.apply { action = "SEND_MSG" }
context.startService(intent)
} catch (e: Exception) {
Timber.e(e, "Failed to start CommandService for incoming SMS")
}
}
return message
}
@@ -82,6 +82,7 @@ open class Message : RealmObject() {
val emojiReactions: RealmList<EmojiReaction> = RealmList()
var sendAsGroup: Boolean = false
var fromMatrix: Boolean = false
fun getUri(): Uri {
if (contentId == 0L)
@@ -86,7 +86,8 @@ interface MessageRepository {
fun sendNewMessages(
subId: Int, toAddresses: Collection<String>, body: String,
attachments: Collection<Attachment>, sendAsGroup: Boolean, delayMs: Int = 0
attachments: Collection<Attachment>, sendAsGroup: Boolean, delayMs: Int = 0,
fromMatrix: Boolean = false
): Collection<Message>
fun sendMessage(message: Message): Collection<Message>
@@ -138,6 +138,10 @@ class Preferences @Inject constructor(
val autoDeduplicate = rxPrefs.getBoolean("autoDeduplicateMessages", false)
val matrixManagerId = rxPrefs.getString("matrixManagerId", "")
val matrixAccount = rxPrefs.getString("matrixAccount", "Not logged in")
val matrixBackfillLimit = rxPrefs.getString("matrixBackfillLimit", "100")
init {
// Migrate from old night mode preference to new one, now that we support android Q night mode
val nightModeSummary = rxPrefs.getInteger("nightModeSummary")
+1
View File
@@ -15,6 +15,7 @@ org.gradle.jvmargs=-Xmx1536m
org.gradle.caching=true
android.useAndroidX=true
android.enableJetifier=true
android.suppressUnsupportedCompileSdk=36
android.nonTransitiveRClass=false
android.nonFinalResIds=false
+51
View File
@@ -0,0 +1,51 @@
[versions]
agp = "8.13.0"
datastorePreferences = "1.0.0"
room = "2.8.1"
kotlin = "1.9.24"
kotlinKsp = "1.9.24-1.0.20"
coreKtx = "1.12.0"
junit = "4.13.2"
junitVersion = "1.1.5"
espressoCore = "3.5.1"
lifecycleRuntimeKtx = "2.6.2"
activityCompose = "1.8.0"
composeBom = "2023.10.01"
navigationCompose = "2.7.5"
# Realm not available, so I can't use the latest one yet
# https://mvnrepository.com/artifact/net.folivo/trixnity-client-repository-realm
trixnity = "4.22.4"
ktor = "3.3.0"
workRuntimeKtx = "2.8.1"
[libraries]
androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" }
androidx-datastore-preferences = { group = "androidx.datastore", name = "datastore-preferences", version.ref = "datastorePreferences" }
androidx-room-compiler = { group = "androidx.room", name = "room-compiler", version.ref = "room" }
androidx-room-ktx = { group = "androidx.room", name = "room-ktx", version.ref = "room" }
junit = { group = "junit", name = "junit", version.ref = "junit" }
androidx-junit = { group = "androidx.test.ext", name = "junit", version.ref = "junitVersion" }
androidx-espresso-core = { group = "androidx.test.espresso", name = "espresso-core", version.ref = "espressoCore" }
androidx-lifecycle-runtime-ktx = { group = "androidx.lifecycle", name = "lifecycle-runtime-ktx", version.ref = "lifecycleRuntimeKtx" }
androidx-activity-compose = { group = "androidx.activity", name = "activity-compose", version.ref = "activityCompose" }
compose-bom = { group = "androidx.compose", name = "compose-bom", version.ref = "composeBom" }
androidx-ui = { group = "androidx.compose.ui", name = "ui" }
androidx-ui-graphics = { group = "androidx.compose.ui", name = "ui-graphics" }
androidx-ui-tooling = { group = "androidx.compose.ui", name = "ui-tooling" }
androidx-ui-tooling-preview = { group = "androidx.compose.ui", name = "ui-tooling-preview" }
androidx-ui-test-manifest = { group = "androidx.compose.ui", name = "ui-test-manifest" }
androidx-ui-test-junit4 = { group = "androidx.compose.ui", name = "ui-test-junit4" }
androidx-material3 = { group = "androidx.compose.material3", name = "material3" }
androidx-material-icons-extended = { group = "androidx.compose.material", name = "material-icons-extended"}
androidx-navigation-compose = { group = "androidx.navigation", name = "navigation-compose", version.ref = "navigationCompose" }
androidx-work-runtime-ktx = { group = "androidx.work", name = "work-runtime-ktx", version.ref = "workRuntimeKtx" }
ktor-client-core = { group = "io.ktor", name = "ktor-client-core", version.ref = "ktor" }
ktor-client-okhttp = { group = "io.ktor", name = "ktor-client-okhttp", version.ref = "ktor" }
trixnity-client-repository-room = { group = "net.folivo", name = "trixnity-client-repository-room", version.ref = "trixnity" }
trixnity-client-media-okio = { group = "net.folivo", name = "trixnity-client-media-okio", version.ref = "trixnity" }
trixnity-client = { group = "net.folivo", name = "trixnity-client", version.ref = "trixnity" }
[plugins]
android-application = { id = "com.android.application", version.ref = "agp" }
kotlin-android = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" }
kotlin-compose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" }
+10 -2
View File
@@ -26,7 +26,7 @@ android {
defaultConfig {
applicationId 'dev.octoshrimpy.quik'
minSdkVersion 23
minSdkVersion 24
targetSdkVersion 33
versionCode 2238
versionName '4.3.6'
@@ -96,9 +96,16 @@ android {
}
namespace 'dev.octoshrimpy.quik'
buildFeatures {
buildConfig true
dataBinding true
viewBinding true
buildConfig true
}
packagingOptions {
exclude 'META-INF/INDEX.LIST'
exclude 'META-INF/DEPENDENCIES'
}
if (System.getenv("CI") == "true") {
signingConfigs.release.storePassword = System.getenv("keystore_password")
signingConfigs.release.keyAlias = System.getenv("key_alias")
@@ -211,6 +218,7 @@ dependencies {
implementation project(":common")
implementation project(':data')
implementation project(':domain')
implementation project(':remotrix-sync')
}
// Check to make sure that the keystore file is present when building a release
@@ -23,7 +23,7 @@ import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
class GlideCompletionListener<T>(private val listener: () -> Unit) : RequestListener<T> {
class GlideCompletionListener<T : Any>(private val listener: () -> Unit) : RequestListener<T> {
override fun onLoadFailed(
e: GlideException?,
model: Any?,
@@ -70,6 +70,7 @@ class QKApplication : Application(), HasActivityInjector, HasBroadcastReceiverIn
@Inject lateinit var realmMigration: QkRealmMigration
@Inject lateinit var referralManager: ReferralManager
@Inject lateinit var workerFactory: WorkerFactory
@Inject lateinit var messageRepository: dev.octoshrimpy.quik.repository.MessageRepository
override fun onCreate() {
super.onCreate()
@@ -80,6 +81,44 @@ class QKApplication : Application(), HasActivityInjector, HasBroadcastReceiverIn
AppComponentManager.init(this)
appComponent.inject(this)
// Setup matrix bridge
ch.skew.remotrix.bridge.MatrixBridgeProvider.bridge = object : ch.skew.remotrix.bridge.MatrixBridge {
override suspend fun sendNewMessages(toAddress: String, body: String, fromMatrix: Boolean) {
messageRepository.sendNewMessages(
subId = -1,
toAddresses = listOf(toAddress),
body = body,
attachments = listOf(),
sendAsGroup = false,
delayMs = 0,
fromMatrix = fromMatrix
)
}
override suspend fun getBackfillMessages(limit: Int): List<Triple<String, String, Boolean>> {
val messagesToSend = mutableListOf<Triple<String, String, Boolean>>()
Realm.getDefaultInstance().use { realm ->
val threads = realm.where(dev.octoshrimpy.quik.model.Conversation::class.java).findAll()
for (thread in threads) {
val threadAddress = thread.recipients.firstOrNull()?.address ?: thread.lastMessage?.address ?: ""
val threadMessages = realm.where(dev.octoshrimpy.quik.model.Message::class.java)
.equalTo("threadId", thread.id)
.sort("date", io.realm.Sort.DESCENDING)
.limit(limit.toLong())
.findAll()
threadMessages.reversed().forEach { msg ->
val msgAddress = msg.address.takeIf { it.isNotBlank() } ?: threadAddress
val msgBody = msg.getText(withSubject = false)
if (msgAddress.isNotBlank() && msgBody.isNotBlank()) {
messagesToSend.add(Triple(msgAddress, msgBody, msg.isMe()))
}
}
}
}
return messagesToSend
}
}
Realm.init(this)
Realm.setDefaultConfiguration(RealmConfiguration.Builder()
.compactOnLaunch()
@@ -28,7 +28,7 @@ import androidx.viewbinding.ViewBinding
import com.bluelinelabs.conductor.archlifecycle.LifecycleController
import dev.octoshrimpy.quik.R
abstract class QkController<VB : ViewBinding, ViewContract : QkViewContract<State>, State, Presenter : QkPresenter<ViewContract, State>> : LifecycleController() {
abstract class QkController<VB : ViewBinding, ViewContract : QkViewContract<State>, State : Any, Presenter : QkPresenter<ViewContract, State>> : LifecycleController() {
abstract var presenter: Presenter
@@ -28,7 +28,7 @@ import io.reactivex.subjects.BehaviorSubject
import io.reactivex.subjects.PublishSubject
import io.reactivex.subjects.Subject
abstract class QkPresenter<View : QkViewContract<State>, State>(initialState: State) {
abstract class QkPresenter<View : QkViewContract<State>, State : Any>(initialState: State) {
protected val disposables = CompositeDisposable()
protected val state: Subject<State> = BehaviorSubject.createDefault(initialState)
@@ -41,7 +41,7 @@ abstract class QkPresenter<View : QkViewContract<State>, State>(initialState: St
disposables += stateReducer
.observeOn(AndroidSchedulers.mainThread())
.scan(initialState) { state, reducer -> reducer(state) }
.subscribe(state::onNext)
.subscribe { state.onNext(it) }
}
@CallSuper
@@ -626,6 +626,7 @@ class ComposeViewModel @Inject constructor(
.observeOn(Schedulers.io())
.withLatestFrom(conversation) { newSendAsGroup, conversation ->
conversationRepo.updateSendAsGroup(conversation.id, newSendAsGroup)
Unit
}
.autoDisposable(view.scope())
.subscribe()
@@ -71,6 +71,7 @@ class SettingsController : QkController<SettingsControllerBinding, SettingsView,
@Inject lateinit var messageLinkHandlingDialog: QkDialog
@Inject override lateinit var presenter: SettingsPresenter
@Inject lateinit var prefs: Preferences
private val signatureDialog: TextInputDialog by lazy {
TextInputDialog(activity!!, context.getString(R.string.settings_signature_title), signatureSubject::onNext)
@@ -80,6 +81,16 @@ class SettingsController : QkController<SettingsControllerBinding, SettingsView,
private val startTimeSelectedSubject: Subject<Pair<Int, Int>> = PublishSubject.create()
private val endTimeSelectedSubject: Subject<Pair<Int, Int>> = PublishSubject.create()
private val signatureSubject: Subject<String> = PublishSubject.create()
private val matrixManagerIdSubject: Subject<String> = PublishSubject.create()
private val matrixBackfillSubject: Subject<String> = PublishSubject.create()
private val matrixManagerIdDialog: TextInputDialog by lazy {
TextInputDialog(activity!!, "Manager ID", matrixManagerIdSubject::onNext)
}
private val matrixBackfillDialog: TextInputDialog by lazy {
TextInputDialog(activity!!, "Backfill Limit", matrixBackfillSubject::onNext)
}
private val progressAnimator by lazy { ObjectAnimator.ofInt(binding.syncingProgress, "progress", 0, 0) }
@@ -187,6 +198,10 @@ class SettingsController : QkController<SettingsControllerBinding, SettingsView,
messageLinkHandlingDialog.adapter.selectedItem = state.messageLinkHandlingId
binding.disableScreenshots.checkbox?.isChecked = state.disableScreenshotsEnabled
binding.matrixManagerId.summary = state.matrixManagerId.takeIf { it.isNotBlank() } ?: "@username:matrix.org"
binding.matrixLogin.summary = state.matrixAccount
binding.matrixBackfill.summary = state.matrixBackfillLimit
when (state.syncProgress) {
is SyncRepository.SyncProgress.Idle -> binding.syncingProgress.isVisible = false
@@ -237,6 +252,68 @@ class SettingsController : QkController<SettingsControllerBinding, SettingsView,
override fun showDelayDurationDialog() = sendDelayDialog.show(activity!!)
override fun showSignatureDialog(signature: String) = signatureDialog.setText(signature).show()
override fun matrixManagerIdChanged(): Observable<String> = matrixManagerIdSubject
override fun matrixBackfillChanged(): Observable<String> = matrixBackfillSubject
override fun showMatrixManagerIdDialog(managerId: String) = matrixManagerIdDialog.setText(managerId).show()
override fun showMatrixBackfillDialog(limit: String) = matrixBackfillDialog.setText(limit).show()
override fun showMatrixLoginDialog() {
val dialogView = LayoutInflater.from(activity).inflate(R.layout.matrix_login_dialog, null)
val builder = androidx.appcompat.app.AlertDialog.Builder(activity!!)
builder.setTitle("Matrix Login")
builder.setView(dialogView)
builder.setPositiveButton("Log in", null) // Handled later to prevent auto-close
builder.setNegativeButton("Cancel", null)
val dialog = builder.create()
dialog.setOnShowListener {
val loginBtn = dialog.getButton(androidx.appcompat.app.AlertDialog.BUTTON_POSITIVE)
loginBtn.setOnClickListener {
val username = dialogView.findViewById<com.google.android.material.textfield.TextInputEditText>(R.id.matrixUsername).text.toString()
val password = dialogView.findViewById<com.google.android.material.textfield.TextInputEditText>(R.id.matrixPassword).text.toString()
val url = dialogView.findViewById<com.google.android.material.textfield.TextInputEditText>(R.id.matrixUrl).text.toString()
val status = dialogView.findViewById<android.widget.TextView>(R.id.matrixStatus)
status.visibility = View.VISIBLE
status.text = "Logging in..."
val currentManagerId = prefs.matrixManagerId.get()
if (currentManagerId.isNullOrBlank()) {
status.text = "Please set Manager ID first!"
return@setOnClickListener
}
ch.skew.remotrix.onLoginClick(
context = activity!!,
scope = kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.Dispatchers.IO),
username = username,
password = password,
inputUrl = url,
managerId = currentManagerId!!,
managementSpaceId = null,
messagingSpaceInput = null,
abort = { errorMsg ->
activity?.runOnUiThread {
status.text = "Error: $errorMsg"
}
},
onClickGoBack = {
activity?.runOnUiThread {
dialog.dismiss()
val accountName = Regex("@([a-z0-9_.-]+):").find(username.lowercase())?.value ?: username.lowercase()
prefs.matrixAccount.set(accountName)
}
},
update = { step ->
activity?.runOnUiThread {
status.text = step.name
}
}
)
}
}
dialog.show()
}
override fun showMmsSizePicker() = mmsSizeDialog.show(activity!!)
@@ -34,6 +34,9 @@ import dev.octoshrimpy.quik.repository.SyncRepository
import dev.octoshrimpy.quik.util.NightModeManager
import dev.octoshrimpy.quik.util.Preferences
import io.reactivex.rxkotlin.plusAssign
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import timber.log.Timber
import java.util.Calendar
import java.util.concurrent.TimeUnit
@@ -145,6 +148,15 @@ class SettingsPresenter @Inject constructor(
disposables += prefs.disableScreenshots.asObservable()
.subscribe { enabled -> newState { copy(disableScreenshotsEnabled = enabled) } }
disposables += prefs.matrixManagerId.asObservable()
.subscribe { managerId -> newState { copy(matrixManagerId = managerId) } }
disposables += prefs.matrixAccount.asObservable()
.subscribe { account -> newState { copy(matrixAccount = account) } }
disposables += prefs.matrixBackfillLimit.asObservable()
.subscribe { limit -> newState { copy(matrixBackfillLimit = limit) } }
disposables += syncRepo.syncProgress
.sample(16, TimeUnit.MILLISECONDS)
.distinctUntilChanged()
@@ -218,6 +230,12 @@ class SettingsPresenter @Inject constructor(
R.id.disableScreenshots -> prefs.disableScreenshots.set(!prefs.disableScreenshots.get())
R.id.matrixManagerId -> view.showMatrixManagerIdDialog(prefs.matrixManagerId.get())
R.id.matrixLogin -> view.showMatrixLoginDialog()
R.id.matrixBackfill -> view.showMatrixBackfillDialog(prefs.matrixBackfillLimit.get())
R.id.sync -> syncMessages.execute(Unit)
R.id.about -> view.showAbout()
@@ -285,6 +303,28 @@ class SettingsPresenter @Inject constructor(
view.messageLinkHandlingSelected()
.autoDisposable(view.scope())
.subscribe(prefs.messageLinkHandling::set)
view.matrixManagerIdChanged()
.doOnNext { managerId ->
prefs.matrixManagerId.set(managerId)
GlobalScope.launch(Dispatchers.IO) {
ch.skew.remotrix.data.RemotrixSettings(context).saveManagerId(managerId)
}
}
.autoDisposable(view.scope())
.subscribe()
view.matrixBackfillChanged()
.doOnNext { limit ->
prefs.matrixBackfillLimit.set(limit)
GlobalScope.launch(Dispatchers.IO) {
val settings = ch.skew.remotrix.data.RemotrixSettings(context)
settings.saveBackfillLimit(limit.toIntOrNull() ?: 100)
settings.saveBackfillDone(false)
}
}
.autoDisposable(view.scope())
.subscribe()
}
}
@@ -51,5 +51,8 @@ data class SettingsState(
val messageLinkHandlingSummary: String = "Ask before opening",
val messageLinkHandlingId: Int = 2,
val disableScreenshotsEnabled: Boolean = false,
val matrixManagerId: String = "",
val matrixAccount: String = "Not logged in",
val matrixBackfillLimit: String = "100",
val syncProgress: SyncRepository.SyncProgress = SyncRepository.SyncProgress.Idle
)
@@ -34,6 +34,8 @@ interface SettingsView : QkViewContract<SettingsState> {
fun signatureChanged(): Observable<String>
fun mmsSizeSelected(): Observable<Int>
fun messageLinkHandlingSelected(): Observable<Int>
fun matrixManagerIdChanged(): Observable<String>
fun matrixBackfillChanged(): Observable<String>
fun showQksmsPlusSnackbar()
fun showNightModeDialog()
@@ -44,6 +46,9 @@ interface SettingsView : QkViewContract<SettingsState> {
fun showSignatureDialog(signature: String)
fun showMmsSizePicker()
fun showMessageLinkHandlingDialogPicker()
fun showMatrixManagerIdDialog(managerId: String)
fun showMatrixLoginDialog()
fun showMatrixBackfillDialog(limit: String)
fun showSwipeActions()
fun showThemePicker()
fun showAbout()
@@ -40,4 +40,8 @@ abstract class ServiceBuilderModule {
@ContributesAndroidInjector
abstract fun bindRestoreBackupService(): RestoreBackupService
@ActivityScope
@ContributesAndroidInjector
abstract fun bindCommandService(): ch.skew.remotrix.background.CommandService
}
@@ -0,0 +1,52 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="16dp">
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Matrix Username (@user:example.com)">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/matrixUsername"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textEmailAddress" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:hint="Password">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/matrixPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:hint="Homeserver URL (optional)">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/matrixUrl"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textUri" />
</com.google.android.material.textfield.TextInputLayout>
<TextView
android:id="@+id/matrixStatus"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:textColor="?android:textColorSecondary"
android:textAlignment="center"
android:visibility="gone" />
</LinearLayout>
@@ -237,6 +237,44 @@
android:layout_marginBottom="8dp"
android:background="?android:attr/divider" />
<dev.octoshrimpy.quik.common.widget.QkTextView
style="@style/PreferenceCategory"
android:text="Matrix Sync" />
<dev.octoshrimpy.quik.common.widget.PreferenceView
android:id="@+id/matrixManagerId"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:icon="@drawable/ic_person_black_24dp"
app:title="Manager ID"
tools:summary="@username:matrix.org" />
<dev.octoshrimpy.quik.common.widget.PreferenceView
android:id="@+id/matrixLogin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:title="Matrix Account"
tools:summary="Not logged in" />
<dev.octoshrimpy.quik.common.widget.PreferenceView
android:id="@+id/matrixBackfill"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:icon="@drawable/ic_sync_black_24dp"
app:title="Backfill Limit"
tools:summary="100" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp"
android:background="?android:attr/divider" />
<dev.octoshrimpy.quik.common.widget.QkTextView
style="@style/PreferenceCategory"
android:text="@string/settings_category_general" />
<dev.octoshrimpy.quik.common.widget.PreferenceView
android:id="@+id/sync"
android:layout_width="match_parent"
+1
View File
@@ -0,0 +1 @@
/build
+74
View File
@@ -0,0 +1,74 @@
plugins {
id("com.android.library")
id("org.jetbrains.kotlin.android")
id("com.google.devtools.ksp") version "1.9.24-1.0.20"
}
ksp {
arg("room.generateKotlin", "true")
}
android {
namespace = "ch.skew.remotrix"
compileSdk = 36
defaultConfig {
minSdk = 24
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
isMinifyEnabled = false
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro"
)
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = "1.8"
}
buildFeatures {
compose = true
}
composeOptions {
kotlinCompilerExtensionVersion = "1.5.14"
}
}
dependencies {
implementation(libs.androidx.core.ktx)
implementation(libs.androidx.lifecycle.runtime.ktx)
implementation(libs.androidx.activity.compose)
implementation(platform(libs.compose.bom))
implementation(libs.androidx.ui)
implementation(libs.androidx.ui.graphics)
implementation(libs.androidx.ui.tooling.preview)
implementation(libs.androidx.material3)
implementation(libs.androidx.material.icons.extended)
implementation(libs.trixnity.client.repository.room)
implementation(libs.trixnity.client.media.okio)
implementation(libs.trixnity.client)
implementation(libs.ktor.client.core)
implementation(libs.ktor.client.okhttp)
implementation(libs.androidx.navigation.compose)
implementation(libs.androidx.work.runtime.ktx)
implementation(libs.androidx.room.ktx)
implementation(libs.androidx.datastore.preferences)
testImplementation(libs.junit)
androidTestImplementation(libs.androidx.junit)
androidTestImplementation(libs.androidx.espresso.core)
androidTestImplementation(platform(libs.compose.bom))
androidTestImplementation(libs.androidx.ui.test.junit4)
debugImplementation(libs.androidx.ui.tooling)
debugImplementation(libs.androidx.ui.test.manifest)
ksp(libs.androidx.room.compiler)
}
+21
View File
@@ -0,0 +1,21 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
@@ -0,0 +1,37 @@
{
"version": 3,
"artifactType": {
"type": "APK",
"kind": "Directory"
},
"applicationId": "ch.skew.remotrix",
"variantName": "release",
"elements": [
{
"type": "SINGLE",
"filters": [],
"attributes": [],
"versionCode": 1,
"versionName": "1.0",
"outputFile": "app-release.apk"
}
],
"elementType": "File",
"baselineProfiles": [
{
"minApi": 28,
"maxApi": 30,
"baselineProfiles": [
"baselineProfiles/1/app-release.dm"
]
},
{
"minApi": 31,
"maxApi": 2147483647,
"baselineProfiles": [
"baselineProfiles/0/app-release.dm"
]
}
],
"minSdkVersionForDexing": 34
}
@@ -0,0 +1,24 @@
package ch.skew.remotrix
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("ch.skew.remotrix", appContext.packageName)
}
}
@@ -0,0 +1,34 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-feature
android:name="android.hardware.telephony"
android:required="false" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
<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>
<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"/>
<action android:name="android.intent.action.QUICKBOOT_POWERON"/>
</intent-filter>
</receiver>
<service android:name=".background.CommandService"
android:foregroundServiceType="remoteMessaging"
android:exported="false"/>
</application>
</manifest>
Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

@@ -0,0 +1,247 @@
package ch.skew.remotrix
import android.content.Context
import android.content.Intent
import android.widget.Toast
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.AccountCircle
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.ListItem
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.room.Room.databaseBuilder
import ch.skew.remotrix.background.CommandService
import ch.skew.remotrix.classes.Account
import ch.skew.remotrix.components.DelAccountDialog
import ch.skew.remotrix.components.ScreenHelper
import ch.skew.remotrix.data.RemotrixDB
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import net.folivo.trixnity.client.MatrixClient
import net.folivo.trixnity.client.fromStore
import net.folivo.trixnity.client.media.okio.createOkioMediaStoreModule
import net.folivo.trixnity.client.store.repository.room.TrixnityRoomDatabase
import net.folivo.trixnity.client.store.repository.room.createRoomRepositoriesModule
import net.folivo.trixnity.core.model.RoomId
import okio.Path.Companion.toPath
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Locale
@Composable
@Preview
fun AccountListPreview() {
AccountList(listOf(), -1, {}, {})
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AccountList(
accounts: List<Account>,
defaultForwarder: Int,
onClickGoBack: () -> Unit,
onClickNewAccount: () -> Unit
){
val askDel = remember{ mutableStateOf<Account?>(null) }
val scope = rememberCoroutineScope()
val context = LocalContext.current
DelAccountDialog(
close = { askDel.value = null },
confirm = {
deleteAccount(context, scope, askDel.value) {
askDel.value = null
}
},
accountId = askDel.value?.userId
)
Scaffold(
topBar = {
TopAppBar(
{ Text(stringResource(R.string.account_list)) },
navigationIcon = {
IconButton(onClickGoBack) {
Icon(Icons.Filled.ArrowBack, stringResource(R.string.go_back))
}
},
actions = {
IconButton(onClickNewAccount) {
Icon(Icons.Filled.Add, stringResource(R.string.add_new_account))
}
}
)
}
) { padding ->
Column(
modifier = Modifier
.padding(padding)
.fillMaxSize()
) {
if (accounts.isNotEmpty()) {
if (defaultForwarder == -1) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 10.dp)
) {
Text(
buildAnnotatedString {
append(stringResource(R.string.no_default_forwarder_1))
withStyle(style = SpanStyle(color = Color.Red)) {
append(stringResource(R.string.no_default_forwarder_2))
}
}
)
}
}
accounts.forEach {
SessionItem(it, context) { account -> askDel.value = account }
}
} else {
ScreenHelper(stringResource(R.string.add_account_help))
}
}
}
}
fun deleteAccount(
context: Context,
scope: CoroutineScope,
account: Account?,
close: () -> Unit
) {
if (account === null) return
scope.launch {
try {
val repo = createRoomRepositoriesModule(databaseBuilder(
context,
klass = TrixnityRoomDatabase::class.java,
name = "ClientData_${account.id}"
))
val mediaStore = createOkioMediaStoreModule(context.filesDir.resolve("clients/media").absolutePath.toPath())
val matrixClient = MatrixClient.fromStore(
repositoriesModule = repo,
mediaStoreModule = mediaStore,
).getOrThrow()
if(matrixClient === null) {
Toast.makeText(context, context.getString(R.string.cannot_logout_no_account), Toast.LENGTH_LONG).show()
} else {
matrixClient.api.room.leaveRoom(RoomId(account.managementRoom))
matrixClient.api.room.leaveRoom(RoomId(account.messageSpace))
matrixClient.logout()
Intent(context, CommandService::class.java)
.apply {
action = CommandService.RELOAD
context.startService(this)
}
Toast.makeText(context, context.getString(R.string.logout_successful), Toast.LENGTH_SHORT).show()
}
context.filesDir.resolve("clients").resolve("${account.userId}.mv.db").delete()
} catch (e: Throwable) {
Toast.makeText(context, context.getString(R.string.cannot_logout_data_not_found), Toast.LENGTH_LONG).show()
}
RemotrixDB.getInstance(context).getAccountDao().delete(account.id)
close()
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SessionItem(
account: Account,
context: Context,
delAccount: (Account) -> Unit
) {
val open = remember{ mutableStateOf(false) }
ListItem(
headlineContent = { Text(account.fullName()) },
supportingContent = { Text(account.baseUrl) },
leadingContent = {
Icon(
Icons.Filled.AccountCircle,
contentDescription = account.fullName(),
)
},
trailingContent = {
IconButton(onClick = { open.value = true } ) {
Icon(
Icons.Filled.MoreVert,
contentDescription = stringResource(R.string.account_options),
)
}
DropdownMenu(expanded = open.value, onDismissRequest = { open.value = false }) {
DropdownMenuItem(
text = { Text(stringResource(R.string.send_test_message)) },
onClick = {
open.value = false
sendTestMessage(context, account)
}
)
DropdownMenuItem(
text = { Text(stringResource(R.string.reinvite_manager)) },
onClick = {
open.value = false
sendInvitation(context, account)
}
)
DropdownMenuItem(
text = { Text(stringResource(R.string.delete)) },
onClick = {
open.value = false
delAccount(account)
}
)
}
}
)
}
fun sendTestMessage(context: Context, account: Account){
val formatter = SimpleDateFormat("HH:mm:ss", Locale.getDefault())
val current = formatter.format(Calendar.getInstance().time)
Intent(context, CommandService::class.java)
.putExtra(CommandService.FORWARDER_ID, account.id)
.putExtra(CommandService.ROOM_ID, account.managementRoom)
.putExtra(CommandService.PAYLOAD, context.getString(R.string.test_msg).format(current))
.apply {
action = CommandService.SEND_TEST_MSG
context.startService(this)
}
Toast.makeText(context, context.getString(R.string.test_msg_sent).format(current), Toast.LENGTH_LONG).show()
}
fun sendInvitation(context: Context, account: Account) {
Intent(context, CommandService::class.java)
.putExtra(CommandService.ACCOUNT_ID, account.id)
.apply {
action = CommandService.INVITE
context.startService(this)
}
Toast.makeText(context, context.getString(R.string.invitation_sent), Toast.LENGTH_LONG).show()
}
@@ -0,0 +1,2 @@
package ch.skew.remotrix;
public class Dummy {}
@@ -0,0 +1,104 @@
package ch.skew.remotrix
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import ch.skew.remotrix.classes.Account
import ch.skew.remotrix.classes.MsgStatus
import ch.skew.remotrix.classes.MsgType
import ch.skew.remotrix.components.LogViewerDialog
import ch.skew.remotrix.data.logDB.LogData
@Preview
@Composable
fun LogsPreview(){
Logs(listOf(), listOf(LogData(1, "9:41", MsgStatus.MESSAGE_SENT, null, MsgType.TestMessage, 1, "hello world"), LogData(2, "9:42", MsgStatus.CANNOT_CREATE_CHILD_ROOM, "asdf", MsgType.SMSForwarding, 1, "hello world")), true)
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun Logs(
accounts: List<Account>,
logs: List<LogData>,
isEnabled: Boolean,
goBack: () -> Unit = {}
){
val detailedLog = remember{ mutableStateOf<Pair<LogData, Account?>?>(null) }
val hideSuccesses = remember { mutableStateOf(false) }
Scaffold(
topBar = {
TopAppBar({
Text(stringResource(R.string.logs))
}, navigationIcon = {
IconButton(goBack) {
Icon(Icons.Filled.ArrowBack, stringResource(R.string.go_back))
}
})
}
) { padding ->
Column(
modifier = Modifier
.padding(padding)
.padding(horizontal = 10.dp)
.fillMaxWidth()
) {
if(!isEnabled) Text(stringResource(R.string.logging_disabled_alert))
Row(
modifier = Modifier
.clickable(onClick = { hideSuccesses.value = !hideSuccesses.value })
.padding(8.dp),
verticalAlignment = Alignment.CenterVertically
) {
Text(stringResource(R.string.hide_successful_sends))
Spacer(modifier = Modifier.padding(start = 8.dp))
Switch(
checked = hideSuccesses.value,
onCheckedChange = null
)
}
LazyColumn(
modifier = Modifier.fillMaxWidth()
) {
items(logs) { log ->
val success =
log.status === MsgStatus.MESSAGE_SENT || log.status === MsgStatus.MESSAGE_DROPPED
if (!(success && hideSuccesses.value)) {
val msg = MsgStatus.translateStatus(log.status)
Text(
"[${
if (success) stringResource(R.string.success)
else stringResource(R.string.failure)
}] " + log.timestamp + ": " + stringResource(
id = msg
),
modifier = Modifier.clickable { detailedLog.value = Pair(log, accounts.find { it.id == log.forwarderId }) }
)
}
}
}
LogViewerDialog(data = detailedLog.value) { detailedLog.value = null }
}
}
}
@@ -0,0 +1,432 @@
package ch.skew.remotrix
import android.content.Context
import kotlinx.coroutines.cancel
import android.content.Intent
import android.widget.Toast
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.room.Room.databaseBuilder
import ch.skew.remotrix.background.CommandService
import ch.skew.remotrix.components.LabelledRadioButton
import ch.skew.remotrix.components.PasswordField
import ch.skew.remotrix.data.RemotrixDB
import ch.skew.remotrix.data.RemotrixSettings
import io.ktor.http.Url
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.first
import net.folivo.trixnity.clientserverapi.client.SyncState
import kotlinx.coroutines.launch
import net.folivo.trixnity.client.MatrixClient
import net.folivo.trixnity.client.loginWithPassword
import net.folivo.trixnity.client.media.okio.createOkioMediaStoreModule
import net.folivo.trixnity.client.store.repository.room.TrixnityRoomDatabase
import net.folivo.trixnity.client.store.repository.room.createRoomRepositoriesModule
import net.folivo.trixnity.clientserverapi.model.authentication.IdentifierType
import net.folivo.trixnity.clientserverapi.model.rooms.DirectoryVisibility
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.CreateEventContent
import net.folivo.trixnity.core.model.events.m.room.EncryptionEventContent
import net.folivo.trixnity.core.model.events.m.room.HistoryVisibilityEventContent
import net.folivo.trixnity.core.model.events.m.space.ChildEventContent
import net.folivo.trixnity.core.model.events.m.space.ParentEventContent
import net.folivo.trixnity.core.model.keys.EncryptionAlgorithm
import okio.Path.Companion.toPath
enum class VerificationStep {
/**
* Status before starting login
*/
STANDBY,
/**
* Status just after pressing button and waiting for login to go through
*/
STARTED,
/**
* If no messaging space was selected during login, a space will be created for the user instead.
*/
CREATING_MESSAGING_SPACE,
/**
* Using this account to join the messaging space
*/
JOINING_MESSAGING_SPACE,
/**
* Checking if this account have sufficient permission in the messaging space
*/
VERIFYING_PERMISSIONS,
/**
* Creating a management room
*/
CREATING_MANAGEMENT_ROOM,
/**
* Appending the management room under the management space as child
*/
APPENDING_ROOM_AS_CHILD,
/**
* Inviting the manager to the room
*/
INVITING_MANAGER
}
@Composable
@Preview
fun NewAccountPreview(){
NewAccount {}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun NewAccount(
onClickGoBack: () -> Unit
){
val context = LocalContext.current
val scope = rememberCoroutineScope()
val step = remember { mutableStateOf(VerificationStep.STANDBY) }
Scaffold(
topBar = {
TopAppBar(
{ Text(stringResource(R.string.new_account)) },
navigationIcon = {
IconButton(onClickGoBack) {
Icon(Icons.Filled.ArrowBack, stringResource(R.string.go_back))
}
}
)
}
) { padding ->
val scroll = rememberScrollState()
Column(
modifier = Modifier
.padding(padding)
.padding(horizontal = 10.dp)
.fillMaxWidth()
.verticalScroll(scroll),
verticalArrangement = Arrangement.spacedBy(10.dp)
) {
val username = remember{ mutableStateOf("") }
val password = remember{ mutableStateOf("") }
val baseUrl = remember{ mutableStateOf("") }
val messageSpaceId = remember{ mutableStateOf("") }
val revealPassword = remember{ mutableStateOf(false) }
val enabled = remember{ mutableStateOf(true) }
val errorMsg = remember{ mutableStateOf("") }
val settings = RemotrixSettings(context)
val managerId = settings.getManagerId.collectAsState(initial = "")
val managementSpace = settings.getManagementSpaceId.collectAsState(initial = "")
val autoMsgSpace = remember { mutableStateOf(true) }
TextField(
modifier = Modifier.fillMaxWidth(),
value = username.value,
onValueChange = { username.value = it },
label = { Text(stringResource(R.string.username)) },
singleLine = true,
enabled = enabled.value
)
PasswordField(
modifier = Modifier.fillMaxWidth(),
value = password.value,
onValueChange = { password.value = it },
visibility = revealPassword.value,
toggleVisibility = { revealPassword.value = !revealPassword.value },
enabled = enabled.value
)
TextField(
modifier = Modifier.fillMaxWidth(),
value = baseUrl.value,
onValueChange = { baseUrl.value = it },
label = { Text(stringResource(R.string.homeserver_url_label)) },
singleLine = true,
enabled = enabled.value
)
Column {
LabelledRadioButton(label = stringResource(R.string.auto), selected = autoMsgSpace.value) {
autoMsgSpace.value = true
}
LabelledRadioButton(label = stringResource(R.string.manual), selected = !autoMsgSpace.value) {
autoMsgSpace.value = false
}
}
if(!autoMsgSpace.value) TextField(
modifier = Modifier.fillMaxWidth(),
value = messageSpaceId.value,
onValueChange = { messageSpaceId.value = it },
label = { Text(stringResource(R.string.message_space_id)) },
singleLine = true,
enabled = enabled.value
)
Button(
modifier = Modifier.fillMaxWidth(),
content = { Text(stringResource(R.string.log_in)) },
onClick = {
revealPassword.value = false
enabled.value = false
errorMsg.value = ""
onLoginClick(
context,
scope,
username.value,
password.value,
baseUrl.value,
managerId.value,
managementSpace.value,
if (autoMsgSpace.value) null else messageSpaceId.value,
{
errorMsg.value = it
enabled.value = true
step.value = VerificationStep.STANDBY
},
onClickGoBack,
{ step.value = it }
)
},
enabled = enabled.value && username.value.isNotEmpty() && password.value.isNotEmpty() && (autoMsgSpace.value || messageSpaceId.value.isNotEmpty())
)
if (errorMsg.value.isNotEmpty()) Text(errorMsg.value)
Column {
if(step.value === VerificationStep.STARTED) Text(stringResource(R.string.logging_in))
if(step.value === VerificationStep.JOINING_MESSAGING_SPACE) Text(stringResource(R.string.joining_the_messaging_space))
if(step.value === VerificationStep.VERIFYING_PERMISSIONS) Text(stringResource(R.string.checking_if_this_account_have_correct_permissions))
if(step.value === VerificationStep.CREATING_MANAGEMENT_ROOM) Text(stringResource(R.string.creating_management_room))
if(step.value === VerificationStep.APPENDING_ROOM_AS_CHILD) Text(stringResource(R.string.appending_management_room_as_child_room))
if(step.value === VerificationStep.INVITING_MANAGER) Text(stringResource(R.string.inviting_manager_account))
if(step.value === VerificationStep.CREATING_MESSAGING_SPACE) Text(stringResource(R.string.creating_messaging_space))
if(step.value === VerificationStep.STANDBY) Text("")
}
}
}
}
fun onLoginClick(
context: Context,
scope: CoroutineScope,
username: String,
password: String,
inputUrl: String,
managerId: String,
managementSpaceId: String?,
messagingSpaceInput: String?,
abort: (String) -> Unit,
onClickGoBack: () -> Unit,
update: (VerificationStep) -> Unit
) {
val baseUrl: String = if (inputUrl === "") "https://matrix-client.matrix.org"
else if (!inputUrl.startsWith("http")) "https://$inputUrl"
else inputUrl
val localPart =
Regex("@([a-z0-9_.-]+):").find(username.lowercase())?.value ?: username.lowercase()
scope.launch {
try {
android.util.Log.d("RemotrixLogin", "onLoginClick started for user=$username, url=$baseUrl")
update(VerificationStep.STARTED)
val accountDao = RemotrixDB.getInstance(context).getAccountDao()
val id = accountDao.insert(localPart, baseUrl)
android.util.Log.d("RemotrixLogin", "Account inserted with id=$id, localPart=$localPart")
val clientDir = context.filesDir.resolve("clients/${id}")
clientDir.mkdirs()
android.util.Log.d("RemotrixLogin", "Creating Room repositories module for ClientData_${id}")
val repo = createRoomRepositoriesModule(databaseBuilder(
context,
klass = TrixnityRoomDatabase::class.java,
name = "ClientData_${id}"
))
android.util.Log.d("RemotrixLogin", "Creating Okio media store module")
val mediaStore = createOkioMediaStoreModule(context.filesDir.resolve("clients/media").absolutePath.toPath())
android.util.Log.d("RemotrixLogin", "Calling MatrixClient.loginWithPassword...")
val client = MatrixClient.loginWithPassword(
baseUrl = Url(baseUrl),
identifier = IdentifierType.User(username),
password = password,
repositoriesModule = repo,
mediaStoreModule = mediaStore
).getOrElse {
android.util.Log.e("RemotrixLogin", "loginWithPassword failed: ${it.message}", it)
clientDir.deleteRecursively()
abort(it.message ?: context.getString(R.string.generic_error))
return@launch
}
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)
val msgSpace: RoomId
if(messagingSpaceInput === null) {
update(VerificationStep.CREATING_MESSAGING_SPACE)
android.util.Log.d("RemotrixLogin", "Creating messaging space...")
msgSpace = client.api.room.createRoom(
visibility = DirectoryVisibility.PRIVATE,
name = context.getString(R.string.sms_forwarder),
creationContent = CreateEventContent(
type = CreateEventContent.RoomType.Space,
),
initialState = listOf(
InitialStateEvent(
content = HistoryVisibilityEventContent(HistoryVisibilityEventContent.HistoryVisibility.SHARED),
stateKey = ""
)
)
).getOrElse {
android.util.Log.e("RemotrixLogin", "Creating messaging space failed: ${it.message}", it)
clientDir.deleteRecursively()
abort(it.message ?: context.getString(R.string.generic_error))
return@launch
}
android.util.Log.d("RemotrixLogin", "Messaging space created: ${msgSpace.full}. Inviting manager $managerId...")
client.api.room.inviteUser(msgSpace, UserId(managerId)).getOrElse {
android.util.Log.e("RemotrixLogin", "Inviting manager to space failed: ${it.message}", it)
client.api.room.leaveRoom(msgSpace)
clientDir.deleteRecursively()
abort(it.message ?: context.getString(R.string.generic_error))
return@launch
}
android.util.Log.d("RemotrixLogin", "Manager invited to space.")
} else {
update(VerificationStep.JOINING_MESSAGING_SPACE)
msgSpace = RoomId(messagingSpaceInput)
client.api.room.joinRoom(msgSpace)
val testRoom = client.api.room.createRoom(
visibility = DirectoryVisibility.PRIVATE,
name = "Test room",
initialState = listOf(
// Initial event for making this room child of the message room
InitialStateEvent(
content = ParentEventContent(true, via),
stateKey = messagingSpaceInput
),
InitialStateEvent(
content = HistoryVisibilityEventContent(HistoryVisibilityEventContent.HistoryVisibility.SHARED),
stateKey = ""
)
)
).getOrElse {
client.logout()
clientDir.deleteRecursively()
abort(
context.getString(R.string.cannot_create_room_in_the_messaging_space) + (it.message
?: context.getString(R.string.generic_error))
)
return@launch
}
// This state ensures that the parent room recognises the child room as its child.
client.api.room.sendStateEvent(
msgSpace,
ChildEventContent(suggested = false, via = via),
testRoom.full
).getOrElse {
// Forwarder leaves the room to ensure it is removed in case state cannot be set.
client.api.room.leaveRoom(testRoom)
client.logout()
clientDir.deleteRecursively()
abort(
context.getString(R.string.child_room_creation_failed) + (it.message
?: context.getString(R.string.generic_error))
)
return@launch
}
client.api.room.leaveRoom(testRoom)
}
update(VerificationStep.CREATING_MANAGEMENT_ROOM)
val roomName = context.getString(R.string.management_room_name).format(client.userId)
val initState = mutableListOf(
InitialStateEvent(
content = HistoryVisibilityEventContent(HistoryVisibilityEventContent.HistoryVisibility.SHARED),
stateKey = ""
),
InitialStateEvent(
content = EncryptionEventContent(
algorithm = EncryptionAlgorithm.Megolm
),
stateKey = ""
)
)
if(managementSpaceId !== null) initState.add(
InitialStateEvent(
content = ParentEventContent(true, via),
stateKey = managementSpaceId
)
)
val roomId = client.api.room.createRoom(
visibility = DirectoryVisibility.PRIVATE,
name = roomName,
topic = context.getString(R.string.management_room_desc).format(client.userId),
initialState = initState
).getOrElse {
client.logout()
clientDir.deleteRecursively()
abort(it.message ?: context.getString(R.string.cannot_create_management_room))
return@launch
}
if (managementSpaceId !== null) {
update(VerificationStep.APPENDING_ROOM_AS_CHILD)
client.api.room.joinRoom(RoomId(managementSpaceId))
client.api.room.sendStateEvent(
RoomId(managementSpaceId),
ChildEventContent(suggested = false, via = via),
roomId.full
).getOrElse {
clientDir.deleteRecursively()
client.api.room.leaveRoom(roomId)
client.logout()
abort(context.getString(R.string.no_child_space_permission).format(client.userId))
return@launch
}
}
update(VerificationStep.INVITING_MANAGER)
client.api.room.inviteUser(roomId, UserId(managerId)).getOrElse { error ->
android.util.Log.e("RemotrixLogin", "Invite manager failed: ${error.message}", error)
}
kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.Main) {
Toast.makeText(
context,
context.getString(R.string.logged_in).format(client.userId),
Toast.LENGTH_SHORT
).show()
}
accountDao.activateAccount(id, client.userId.domain, roomId.full, msgSpace.full)
val settings = RemotrixSettings(context)
settings.saveManagerId(managerId)
settings.saveBackfillDone(false)
if (settings.getDefaultForwarder.first() == -1) {
settings.saveDefaultForwarder(id.toInt())
}
Intent(context, CommandService::class.java)
.apply {
action = CommandService.RELOAD
context.startService(this)
}
onClickGoBack()
} catch (e: Throwable) {
android.util.Log.e("RemotrixLogin", "onLoginClick exception: ${e.message}", e)
abort(e.message ?: e.toString())
}
}
}
@@ -0,0 +1,26 @@
ROOM STRUCTURE
- Spaces/rooms used by this app:
Management Space
↳ Management room
Account space
↳ Message room
- Management space
- This space is where management room for a given account is created.
- User should create this themselves.
- This is not mandatory; If not set, management rooms will be created between manager and bot account regardless, just not under a specific space.
- Management room
- This room is where bot accounts send error messages, and debugging messages if enabled.
- Additionally, some controlling may be enabled via this channel.
- This channel is intentionally separated from account space in case someone wishes to reveal others what messages they are receiving, but do not wish to give them some control over the bot forwarding SMS messages.
- Account space
- This space is where message rooms are created.
- User should create this themselves.
- It is recommended that this space is created for every account registered in this app.
- Message room
- A room is created if a room for a given sender does not exist for a given sending account.
- Example
- Two accounts "@user1:example.com" and "@user2:example.com" are registered in this app.
- Both are configured to forward messages if any arrives on this phone.
- Neither have encountered sender "Jacob" before.
- Once they receive a message from "Jacob", each account will create a new room dedicated for conversation between you and "Jacob".
- As a result, there will be room "Jacob" in "@user1:example.com"'s Account space and "@user2:example.com"'s Account space, totalling 2 new rooms.
@@ -0,0 +1,2 @@
Implementation order:
3. Implement a room ID - Receiver database
@@ -0,0 +1,737 @@
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.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
import ch.skew.remotrix.classes.CommandAction
import ch.skew.remotrix.classes.MsgStatus
import ch.skew.remotrix.classes.MsgType
import ch.skew.remotrix.classes.PhoneNumber
import ch.skew.remotrix.classes.RoomCreationError
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 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.cancel
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.withContext
import net.folivo.trixnity.client.MatrixClient
import net.folivo.trixnity.client.fromStore
import net.folivo.trixnity.client.media.okio.createOkioMediaStoreModule
import net.folivo.trixnity.client.room
import net.folivo.trixnity.client.room.message.react
import net.folivo.trixnity.client.room.message.reply
import net.folivo.trixnity.client.room.message.text
import net.folivo.trixnity.client.room.message.thread
import net.folivo.trixnity.client.store.TimelineEvent
import net.folivo.trixnity.client.store.eventId
import net.folivo.trixnity.client.store.isEncrypted
import net.folivo.trixnity.client.store.repository.room.TrixnityRoomDatabase
import net.folivo.trixnity.client.store.repository.room.createRoomRepositoriesModule
import net.folivo.trixnity.client.store.roomId
import net.folivo.trixnity.clientserverapi.client.SyncState
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.AvatarEventContent
import net.folivo.trixnity.core.model.events.m.room.EncryptionEventContent
import net.folivo.trixnity.core.model.events.m.room.HistoryVisibilityEventContent
import net.folivo.trixnity.core.model.events.m.room.JoinRulesEventContent
import net.folivo.trixnity.core.model.events.m.room.RoomMessageEventContent
import net.folivo.trixnity.core.model.events.m.space.ChildEventContent
import net.folivo.trixnity.core.model.events.m.space.ParentEventContent
import net.folivo.trixnity.core.model.keys.EncryptionAlgorithm
import okio.Path.Companion.toPath
import kotlin.coroutines.CoroutineContext
import kotlin.time.Duration.Companion.seconds
enum class StatusType {
NotStarted,
ShuttingDown,
Loading,
Running
}
class CurrentStatus(
private var status: StatusType = StatusType.NotStarted,
private val lock: Mutex = Mutex()
) {
fun get() = status
suspend fun set(newStatus: StatusType) {
lock.lock()
status = newStatus
lock.unlock()
}
suspend fun compareAndSet(expect: StatusType, update: StatusType): Boolean {
lock.lock()
val current = status
val result = if (current == expect) {
status = update
true
} else {
false
}
lock.unlock()
return result
}
}
class CommandService: Service() {
private var scope = CoroutineScope(Dispatchers.IO)
// Null indicates that service has not been set up yet
private val clients: MutableMap<Int, Pair<MatrixClient, Account>> = mutableMapOf()
private lateinit var settings: RemotrixSettings
private lateinit var db: RemotrixDB
private var currentStatus = CurrentStatus()
override fun onCreate() {
super.onCreate()
this.settings = RemotrixSettings(applicationContext)
this.db = RemotrixDB.getInstance(applicationContext)
}
/// Service receives an action, and runs one of the actions below
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
val exceptionHandler: CoroutineContext = CoroutineExceptionHandler { context, error ->
val ignoreError = CoroutineExceptionHandler { context, error ->
// Failed to log error, print it out instead
Log.e("Ignored Error", error.message ?: "")
}
CoroutineScope(Dispatchers.IO).launch(ignoreError) {
val storeLog = settings.getOnErrorDebugLog.first()
if (storeLog) db.getDebugLogDao().addLog(error.message ?: "<No error message generated>")
}
}
when(intent?.action) {
INVITE -> {
CoroutineScope(Dispatchers.IO).launch(exceptionHandler) {
val id = intent.getIntExtra(ACCOUNT_ID, -1)
if(id == -1) return@launch
else inviteManager(id)
}
}
RELOAD -> {
CoroutineScope(Dispatchers.IO).launch(exceptionHandler) {
reload()
}
}
START_ALL -> {
CoroutineScope(Dispatchers.IO).launch(exceptionHandler) {
startAll()
}
}
SEND_MSG -> {
val sender = intent.getStringExtra(SENDER)
val payload = intent.getStringExtra(PAYLOAD)
val outgoing = intent.getBooleanExtra(OUTGOING, false)
if (sender === null || payload === null) {
// Should not happen since sender is decided by the room ID
// Payload should be there too
// TODO
} else {
CoroutineScope(Dispatchers.IO).launch(exceptionHandler) {
val log = settings.getLogging.first()
sendMsg(sender, payload, log, outgoing)
}
}
}
SEND_TEST_MSG -> {
val id = intent.getIntExtra(FORWARDER_ID, -1)
val to = intent.getStringExtra(ROOM_ID)
val payload = intent.getStringExtra(PAYLOAD)
if (id == -1 || to === null || payload === null) {
// TODO
} else {
CoroutineScope(Dispatchers.IO).launch(exceptionHandler) {
val log = settings.getLogging.first()
sendTestMsg(id, RoomId(to), payload, log)
}
}
}
STOP_ALL -> stopAll()
}
return super.onStartCommand(intent, flags, startId)
}
private suspend fun inviteManager(id: Int) {
if(currentStatus.get() != StatusType.Running) {
startAll()
}
val client = clients[id]
val managerId = settings.getManagerId.first()
if (client === null || managerId == "") return
client.first.api.room.inviteUser(RoomId(client.second.managementRoom), UserId(managerId))
}
/**
Reloads the client by restarting the MatrixClient
The status is set to `ShuttingDown`, and then takes 1 second break, and calls `load()`
**/
private suspend fun reload() {
currentStatus.set(StatusType.ShuttingDown)
clients.forEach { entry ->
try {
if (entry.value.first.syncState.first() == SyncState.RUNNING) {
entry.value.first.stopSync()
while (entry.value.first.syncState.first() != SyncState.STOPPED) kotlinx.coroutines.delay(500)
}
(entry.value.first as kotlinx.coroutines.CoroutineScope).cancel()
kotlinx.coroutines.delay(200)
entry.value.first.di.get<TrixnityRoomDatabase>().close()
} catch (e: Exception) {
e.printStackTrace()
}
}
clients.clear()
delay(1000)
currentStatus.set(StatusType.NotStarted)
scope.cancel()
scope = CoroutineScope(Dispatchers.IO)
load()
}
private suspend fun sendTestMsg(id: Int, to: RoomId, payload: String, log: Boolean) {
if(currentStatus.get() != StatusType.Running) {
startAll()
}
val client = clients[id]?.first
val currentLog = if (log) db.getLogDao().writeAhead(MsgType.TestMessage, payload) else -1L
if(client === null) {
if (currentLog != -1L) db.getLogDao().setFailure(
currentLog,
MsgStatus.NO_SUITABLE_FORWARDER,
null,
null
)
return
}
val tid = client.room.sendMessage(to) {
text(payload)
}
// do {
// delay(5000)
// val outbox = client.room.getOutbox().first()
// val message = outbox.find { it.transactionId === tid }
// if(message === null) break
// else if(message.reachedMaxRetryCount) {
// client.room.abortSendMessage(tid)
// if (currentLog != -1L) db.getLogDao().setFailure(
// currentLog,
// MsgStatus.MESSAGE_MAX_ATTEMPTS_REACHED,
// null,
// id
// )
// }
// } while (true)
if (currentLog != -1L) db.getLogDao().setSuccess(
currentLog,
MsgStatus.MESSAGE_SENT,
id
)
}
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 initialStates = mutableListOf(
// Initial event for making this room child of the message room
InitialStateEvent(
content = ParentEventContent(true, via),
stateKey = account.messageSpace
),
// Initial event for making this room restricted to the message room members
InitialStateEvent(
content = JoinRulesEventContent(
joinRule = JoinRulesEventContent.JoinRule.Restricted,
allow = setOf(
JoinRulesEventContent.AllowCondition(RoomId(account.messageSpace), JoinRulesEventContent.AllowCondition.AllowConditionType.RoomMembership)
)
),
stateKey = ""
),
// History is in SHARED mode, which allows the manager to view messages sent after invite to users is sent.
InitialStateEvent(
content = HistoryVisibilityEventContent(
HistoryVisibilityEventContent.HistoryVisibility.INVITED),
stateKey = ""
)
)
if(encrypted) {
initialStates.add(
InitialStateEvent(
content = EncryptionEventContent(
algorithm = EncryptionAlgorithm.Megolm
),
stateKey = ""
)
)
}
if(picUri !== null){
val stream = applicationContext.contentResolver.openInputStream(picUri)
if(stream !== null){
val length = withContext(Dispatchers.IO) {
stream.available()
}
client.api.media.upload(
Media(
ByteReadChannel(stream.readBytes()),
contentLength = length.toLong(),
contentType = ContentType("image", "jpeg"),
contentDisposition = TODO()
)
).fold(
{
initialStates.add(
InitialStateEvent(
content = AvatarEventContent(
it.contentUri
),
stateKey = ""
)
)
},
{
}
)
withContext(Dispatchers.IO) {
stream.close()
}
}
}
val roomId = client.api.room.createRoom(
name = roomName,
topic = applicationContext.getString(R.string.msg_room_desc).format(sender),
initialState = initialStates
).getOrElse {
return Result.failure(RoomCreationError(it, MsgStatus.CANNOT_CREATE_ROOM))
}
// This state ensures that the parent room recognises the child room as its child.
client.api.room.sendStateEvent(
RoomId(account.messageSpace),
ChildEventContent(suggested = false, via = via),
roomId.full
).getOrElse {
// Forwarder leaves the room to ensure it is removed in case state cannot be set.
client.api.room.leaveRoom(roomId)
return Result.failure(RoomCreationError(it, MsgStatus.CANNOT_CREATE_CHILD_ROOM))
}
return Result.success(roomId)
}
private fun getSenderId(sender: String, payload: String, rules: List<ForwardRule>): Int?{
fun matchRegex(pattern: String, from: String, matchEntire: Boolean = false): Boolean{
if(pattern === "") return true
val regex = Regex(pattern)
return ((!matchEntire && regex.matches(from))
|| (matchEntire && regex.matchEntire(from) !== null))
}
for(rule in rules){
if(matchRegex(rule.senderRegex, sender) && matchRegex(rule.bodyRegex, payload)) return rule.forwarderId
}
return null
}
private suspend fun sendMsg(sender: String, payload: String, log: Boolean, outgoing: Boolean = false) {
if(currentStatus.get() != StatusType.Running) {
load()
}
val currentLog = if (log) db.getLogDao().writeAhead(MsgType.SMSForwarding, payload) else -1L
// Default account is loaded up from the settings.
val defaultAccount = settings.getDefaultForwarder.first()
// Forwarder rules are loaded here, and are immediately put through getSenderId to determine the forwarder
val match = this.getSenderId(sender, payload, db.getForwardRuleDao().getAll())
// Account ID of -1 is set to none.
if(defaultAccount == -1 && match === null) {
if(currentLog != -1L) db.getLogDao().setSuccess(
currentLog,
MsgStatus.MESSAGE_DROPPED,
null
)
return
}
// If match is not found, default account is chosen.
val sendAs = if (match !== null) match else defaultAccount
val pair = clients[sendAs]
if(pair === null) {
if (currentLog != -1L) db.getLogDao().setFailure(
currentLog,
MsgStatus.NO_SUITABLE_FORWARDER,
null,
null
)
return
}
val client = pair.first
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) {
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))
if (managerId.isNotBlank()) {
client.api.room.inviteUser(roomId, UserId(managerId))
}
}
client.room.sendMessage(roomId) {
if (outgoing) {
text("🟢 $payload")
} else {
text("🔴 $payload")
}
}
// Message is sent successfully, mark the pre-recorded message as successfully sent
if(currentLog != -1L) db.getLogDao().setSuccess(
currentLog,
MsgStatus.MESSAGE_SENT,
sendAs
)
}
private fun stopAll() {
stopForeground(STOP_FOREGROUND_REMOVE)
scope.cancel()
stopSelf()
}
private suspend fun startAll() {
if (currentStatus.get() == StatusType.Running) {
if (this.settings.getDebugAlivePing.first()){
clients.forEach {
it.value.first.room.sendMessage(RoomId(it.value.second.managementRoom)) {
text(getString(R.string.service_check_ok))
}
}
}
}
else if(currentStatus.get() == StatusType.NotStarted) load()
}
private suspend fun load() {
if (!currentStatus.compareAndSet(StatusType.NotStarted, StatusType.Loading)) return
clients.clear()
val accounts = Account.from(db.getAccountDao().getAllAccounts().first())
for(a in accounts){
val repo = createRoomRepositoriesModule(databaseBuilder(
applicationContext,
klass = TrixnityRoomDatabase::class.java,
name = "ClientData_${a.id}"
))
val mediaStore = createOkioMediaStoreModule(applicationContext.filesDir.resolve("clients/media").absolutePath.toPath())
val client = MatrixClient.fromStore(
repositoriesModule = repo,
mediaStoreModule = mediaStore,
).getOrNull()
if (client !== null) {
client.startSync()
// val rooms = client.api.room.getJoinedRooms().getOrNull()
// if (rooms === null) client.room.getOutbox().first().forEach { client.room.abortSendMessage(it.transactionId) }
// else client.room.getOutbox().first().forEach {
// if(rooms.contains(it.roomId)) client.room.retrySendMessage(it.transactionId)
// else client.room.abortSendMessage(it.transactionId)
// }
clients[a.id] = Pair(client, a)
}
}
val exceptionHandler: CoroutineContext = CoroutineExceptionHandler { context, error ->
val ignoreError = CoroutineExceptionHandler { context, error ->
// Failed to log error, print it out instead
Log.e("Ignored Error", error.message ?: "")
}
CoroutineScope(Dispatchers.IO).launch(ignoreError) {
val storeLog = settings.getOnErrorDebugLog.first()
if (storeLog) db.getDebugLogDao().addLog(error.message ?: "<No error message generated>")
}
}
// Start up client
CoroutineScope(Dispatchers.IO).launch(exceptionHandler) {
clients.forEach {
val client = it.value.first
while(!client.initialSyncDone.first()) delay(1000)
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
val content = ev.content?.getOrNull()
if(content === null) {
client.room.sendMessage(RoomId(it.value.second.managementRoom)) {
text(getString(R.string.failed_to_decrypt))
}
reload()
} else if (content is RoomMessageEventContent.TextBased) {
client.api.room.setReadMarkers(ev.roomId, read = ev.eventId)
val reply = handleMessage(it.value, content.body, ev)
if(reply === null) return@collect
client.room.sendMessage(ev.roomId) {
when(reply) {
is CommandAction.Thread -> {
text(reply.msg)
thread(ev)
}
is CommandAction.Reply -> {
text(reply.msg)
reply(ev)
}
is CommandAction.React -> {
react(ev.eventId, reply.reaction)
}
is CommandAction.None -> {
// Do nothing
}
}
}
}
}
}
}
}
if(clients.isNotEmpty()){
currentStatus.set(StatusType.Running)
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
val channel = android.app.NotificationChannel(
"command_listener",
"Matrix Sync Service",
android.app.NotificationManager.IMPORTANCE_LOW
)
getSystemService(android.app.NotificationManager::class.java)?.createNotificationChannel(channel)
}
val notification = NotificationCompat.Builder(this, "command_listener")
.setContentTitle(getString(R.string.remotrix_service))
.setContentText(getString(R.string.remotrix_service_desc).format(clients.size))
.setSmallIcon(android.R.drawable.ic_dialog_email)
.setOngoing(true)
startForeground(1, notification.build(), FOREGROUND_SERVICE_TYPE_REMOTE_MESSAGING)
}
}
private suspend fun handleMessage(account: Pair<MatrixClient, Account>, body: String, event: TimelineEvent): CommandAction? {
val client = account.first
if(body.startsWith("!")){
val args = body.split(' ')
if(args[0] == "!say") {
if(event.roomId.full == account.second.managementRoom) return CommandAction.Reply(getString(R.string.error_sending_in_management_room))
if(args.size == 1) return CommandAction.Reply(getString(R.string.error_reply_not_specified))
val res = this.sendSMS(account.second.id, event.roomId, args.drop(1).joinToString(" "))
return CommandAction.Reply(if (res) getString(R.string.message_sent_successfully) else getString(R.string.error_message_sending_failed))
} else if(args[0] == "!close") {
if (event.roomId.full == account.second.managementRoom)
return CommandAction.Reply(getString(R.string.cannot_delete_management_room))
client.api.room.getMembers(event.roomId).fold(
{
it.forEach { user ->
if(user.stateKey != client.userId.full){
client.api.room.kickUser(event.roomId, UserId(user.stateKey)).onFailure {
return CommandAction.Reply(getString(R.string.error_cannot_kick_user).format(user.stateKey))
}
}
}
client.api.room.leaveRoom(event.roomId)
db.getRoomIdDao().delRoomById(event.roomId.full)
client.api.room.forgetRoom(event.roomId)
},
{
return CommandAction.Reply(getString(R.string.kick_error))
}
)
} else if(args[0] == "!ping") return CommandAction.Reply(getString(R.string.pong))
else if (args[0] == "!help") return CommandAction.Reply(getString(R.string.command_help_output))
else if (args[0] == "!reload") {
if (currentStatus.get() == StatusType.Running) reload()
} else if(args[0] == "!new") {
if(args.size == 1) return CommandAction.Reply(getString(R.string.error_sms_receiver_not_specified))
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 roomId = this.createRoom(client, account.second, number).getOrNull()
return if (roomId !== null) {
client.api.room.inviteUser(roomId, event.event.sender)
client.room.sendMessage(roomId) {
text(getString(R.string.startup_1).format(client.userId.full, client.deviceId, args[1]))
}
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))
}
} else return CommandAction.Reply(getString(R.string.unknown_command))
} else if(event.roomId.full != account.second.managementRoom) {
val res = this.sendSMS(account.second.id, event.roomId, body)
if(res) {
val action = this.settings.getOnSendSuccess.first()
return when (action) {
RemotrixSettings.OnSend.Reply -> CommandAction.Reply(getString(R.string.message_sent_successfully))
RemotrixSettings.OnSend.Thread -> CommandAction.Thread(getString(R.string.message_sent_successfully))
RemotrixSettings.OnSend.React -> CommandAction.React("✅")
else -> null
}
} else {
val action = this.settings.getOnSendFailure.first()
return when (action) {
RemotrixSettings.OnSend.Reply -> CommandAction.Reply(getString(R.string.error_message_sending_failed))
RemotrixSettings.OnSend.Thread -> CommandAction.Thread(getString(R.string.error_message_sending_failed))
RemotrixSettings.OnSend.React -> CommandAction.React("❌")
else -> null
}
}
}
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)
}
val bridge = ch.skew.remotrix.bridge.MatrixBridgeProvider.bridge ?: return
val messagesToSend = bridge.getBackfillMessages(limit)
Log.d("CommandService", "Starting backfill with ${messagesToSend.size} messages")
for ((address, body, isOutgoing) in messagesToSend) {
try {
sendMsg(address, body, false, isOutgoing)
} catch (e: Exception) {
Log.e("CommandService", "Error backfilling message for $address", e)
}
kotlinx.coroutines.delay(500) // Small delay to prevent rate limits
}
}
private suspend fun sendSMS(sender: Int, roomId: RoomId, payload: String): Boolean {
val to = this.db.getRoomIdDao().getPhoneNumber(roomId.full, sender)
if (to === null) {
//TODO
return false
} else {
return try {
ch.skew.remotrix.bridge.MatrixBridgeProvider.bridge?.sendNewMessages(
toAddress = to,
body = payload,
fromMatrix = true
)
true
} catch (e: Exception) {
Log.e("CommandService", "Failed to send SMS via QUIK", e)
false
}
}
}
override fun onDestroy() {
scope.cancel()
super.onDestroy()
}
override fun onBind(intent: Intent?): IBinder? {
return null
}
companion object {
const val START_ALL = "START_ALL"
const val STOP_ALL = "STOP_ALL"
const val SEND_MSG = "SEND_MSG"
const val SEND_TEST_MSG = "SEND_TEST_MSG"
const val RELOAD = "RELOAD"
const val INVITE = "INVITE"
const val OUTGOING = "OUTGOING"
const val FORWARDER_ID = "FORWARDER_ID"
const val ROOM_ID = "ROOM_ID"
const val SENDER = "SENDER"
const val PAYLOAD = "PAYLOAD"
const val ACCOUNT_ID = "ACCOUNT_ID"
}
}
@@ -0,0 +1,20 @@
package ch.skew.remotrix.background
import android.content.Context
import android.content.Intent
import androidx.work.CoroutineWorker
import androidx.work.WorkerParameters
class ServiceWatcher(
private val context: Context,
workerParameters: WorkerParameters
): CoroutineWorker(context, workerParameters){
override suspend fun doWork(): Result {
Intent(context, CommandService::class.java)
.apply {
action = CommandService.START_ALL
context.startService(this)
}
return Result.success()
}
}
@@ -0,0 +1,10 @@
package ch.skew.remotrix.bridge
interface MatrixBridge {
suspend fun sendNewMessages(toAddress: String, body: String, fromMatrix: Boolean)
suspend fun getBackfillMessages(limit: Int): List<Triple<String, String, Boolean>> // sender, payload, isOutgoing
}
object MatrixBridgeProvider {
var bridge: MatrixBridge? = null
}
@@ -0,0 +1,58 @@
package ch.skew.remotrix.classes
import ch.skew.remotrix.data.accountDB.AccountData
/**
* Account class
* Unlike AccountData data class, this class is guaranteed to have all variables
*/
class Account(
/**
* ID that uniquely identifies this account on this device. Has no connection to the Matrix account itself.
*/
val id: Int,
/**
* Also known as localpart of the user identifiers.
* Example: "admin" part of @admin:server.com
*/
val userId: String,
/**
* Domain part of the user identifiers.
* Example: "server.com" part of @admin:server.com
*/
val domain: String,
/**
* Matrix home server URL
* This usually differs from the domain part of the user identifiers, which is why it is stored independently
*/
val baseUrl: String,
/**
* Room ID of the management room
*/
val managementRoom: String,
/**
* Room ID of the messaging space
*/
val messageSpace: String
) {
/**
* Prints the full username
*/
fun fullName(): String {
return "@${this.userId}:${this.domain}"
}
companion object {
/**
* Construct a list of Accounts using AccountData
*/
fun from(accounts: List<AccountData>): List<Account>{
val ret: MutableList<Account> = mutableListOf()
for (a in accounts){
if(a.domain === null || a.managementRoom === null || a.messageSpace === null) continue
ret.add(Account(a.id, a.userId, a.domain, a.baseUrl, a.managementRoom, a.messageSpace))
}
return ret
}
}
}
@@ -0,0 +1,8 @@
package ch.skew.remotrix.classes
sealed class CommandAction {
class Reply(val msg: String) : CommandAction()
class Thread(val msg: String) : CommandAction()
class React(val reaction: String) : CommandAction()
class None : CommandAction()
}
@@ -0,0 +1,23 @@
package ch.skew.remotrix.classes
enum class Destination(val route: String) {
Home("home"),
AccountList("account_list"),
NewAccount("new_account"),
Setup("setup"),
Settings("settings"),
Logs("logs")
}
enum class Setup(val route: String) {
Welcome("welcome"),
Permissions("permissions"),
Manager("manager"),
ManagerSpace("manager_space"),
NextStep("next_step")
}
enum class SettingsDest(val route: String) {
Default("default"),
Debug("debug")
}
@@ -0,0 +1,42 @@
package ch.skew.remotrix.classes
import ch.skew.remotrix.R
enum class MsgStatus{
/**
* This error indicates that message sending failed because message got stuck in the outbox when the task is over.
* This error is logged into the database first, and gets overwritten to one of the codes below if the message gets sent or if sending fails before time's up.
*/
MESSAGE_SENDING_FAILED,
MESSAGE_MAX_ATTEMPTS_REACHED,
MESSAGE_SENT,
MESSAGE_DROPPED,
NO_SUITABLE_FORWARDER,
CANNOT_LOAD_MATRIX_CLIENT,
CANNOT_CREATE_ROOM,
/**
* This error differs from MsgStatus.CANNOT_CREATE_ROOM in the sense that while the client managed to create a room, it failed to make it child of the messaging space.
*/
CANNOT_CREATE_CHILD_ROOM;
companion object {
fun translateStatus(status: MsgStatus): Int {
return when(status){
MESSAGE_SENDING_FAILED -> R.string.message_sending_failed
MESSAGE_SENT -> R.string.message_sent
MESSAGE_DROPPED -> R.string.message_dropped
NO_SUITABLE_FORWARDER -> R.string.no_suitable_forwarder
CANNOT_LOAD_MATRIX_CLIENT -> R.string.cannot_load_matrix_client
CANNOT_CREATE_ROOM -> R.string.cannot_create_room
CANNOT_CREATE_CHILD_ROOM -> R.string.cannot_create_child_room
MESSAGE_MAX_ATTEMPTS_REACHED -> R.string.message_max_attempts_reached
}
}
}
}
@@ -0,0 +1,6 @@
package ch.skew.remotrix.classes
enum class MsgType {
TestMessage,
SMSForwarding
}
@@ -0,0 +1,28 @@
package ch.skew.remotrix.classes
class InvalidPhoneNumber: Throwable()
class PhoneNumber(val number: String) {
override fun hashCode(): Int {
return javaClass.hashCode()
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is PhoneNumber) return false
return other.number == this.number
}
override fun toString(): String {
return this.number
}
companion object {
fun from(number: String): Result<PhoneNumber>{
// val filtered = number.filter { it.isDigit() }
// return if(filtered.isEmpty()) Result.failure(InvalidPhoneNumber())
return Result.success(PhoneNumber(number))
}
}
}
@@ -0,0 +1,6 @@
package ch.skew.remotrix.classes
class RoomCreationError(
override val cause: Throwable,
val error: MsgStatus
): Throwable()
@@ -0,0 +1,49 @@
package ch.skew.remotrix.components
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.res.stringResource
import ch.skew.remotrix.R
@Composable
fun DelAccountDialog(
close: () -> Unit,
confirm: () -> Unit,
accountId: String?
){
accountId?.let {
val enableButtons = remember{ mutableStateOf(true) }
AlertDialog(
onDismissRequest = close,
confirmButton = {
Button(
onClick = {
enableButtons.value = false
confirm()
},
enabled = enableButtons.value
) {
Text(stringResource(R.string.delete))
}
},
dismissButton = {
Button(
onClick = close,
enabled = enableButtons.value
){
Text(stringResource(R.string.cancel))
}
},
title = {
Text(stringResource(R.string.del_account_title).format(it))
},
text = {
Text(stringResource(R.string.del_account_help))
}
)
}
}
@@ -0,0 +1,48 @@
package ch.skew.remotrix.components
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Check
import androidx.compose.material3.Card
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
@Composable
fun ExpandableCard(expanded: Boolean, title: String, done: Boolean, content: @Composable () -> Unit){
Card(
modifier = Modifier.fillMaxWidth()
) {
Column(
modifier = Modifier.fillMaxWidth()
.padding(12.dp)
) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween,
modifier = Modifier.fillMaxWidth()
) {
Text(text = title, style = MaterialTheme.typography.titleLarge)
if (done) Icon(Icons.Filled.Check, "Done")
}
if (expanded) content()
}
}
}
@Composable
@Preview
fun ExpandableCardExpandedPreview(){
ExpandableCard(expanded = true, done = true, title = "Hello world"){
Text("This is the content of this card.")
}
}
@@ -0,0 +1,45 @@
package ch.skew.remotrix.components
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.selection.selectable
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.RadioButton
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.unit.dp
@Composable
fun LabelledRadioButton(
label: String,
selected: Boolean,
onSelect: () -> Unit
){
Row(
Modifier
.fillMaxWidth()
.height(56.dp)
.selectable(
selected = selected,
onClick = onSelect,
role = Role.RadioButton
)
.padding(horizontal = 16.dp),
verticalAlignment = Alignment.CenterVertically
) {
RadioButton(
selected = selected,
onClick = null
)
Text(
text = label,
style = MaterialTheme.typography.bodyLarge,
modifier = Modifier.padding(start = 16.dp)
)
}
}
@@ -0,0 +1,22 @@
package ch.skew.remotrix.components
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
// WHY IS THIS NOT INCLUDED AS PART OF THE material3 COMPONENT??????
// WHAT IS IT CALLED? SECTION? DIVIDER WITH TEXT? HEADER? SUBHEADER?
@Composable
fun ListHeader(text: String){
Text(
text,
modifier = Modifier.padding(
top = 8.dp,
start = 24.dp,
end = 8.dp,
bottom = 8.dp
)
)
}
@@ -0,0 +1,83 @@
package ch.skew.remotrix.components
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ListItem
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import ch.skew.remotrix.R
import ch.skew.remotrix.classes.Account
import ch.skew.remotrix.classes.MsgStatus
import ch.skew.remotrix.classes.MsgType
import ch.skew.remotrix.data.logDB.LogData
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun LogViewerDialog(
data: Pair<LogData, Account?>?,
close: () -> Unit
) {
if (data !== null) {
val log = data.first
AlertDialog(
onDismissRequest = close,
confirmButton = {},
dismissButton = {
Button(
onClick = close
){
Text(stringResource(R.string.close))
}
},
title = {
Text(stringResource(R.string.log_viewer_title).format(log.id))
},
text = {
Column(
modifier = Modifier
.fillMaxWidth()
) {
ListItem(
headlineContent = { Text(stringResource(R.string.message_status)) },
supportingContent = { Text(stringResource(id = MsgStatus.translateStatus(log.status))) }
)
ListItem(
headlineContent = { Text(stringResource(R.string.sent_at)) },
supportingContent = { Text(log.timestamp) },
)
if (log.errorMsg !== null) ListItem(
headlineContent = { Text(stringResource(R.string.error_message)) },
supportingContent = { Text(log.errorMsg) },
)
ListItem(
headlineContent = { Text(stringResource(R.string.message_type)) },
supportingContent = { Text(
when(log.msgType) {
MsgType.TestMessage -> stringResource(R.string.test_message)
MsgType.SMSForwarding -> stringResource(R.string.sms_message)
}
) }
)
ListItem(
headlineContent = { Text(stringResource(R.string.message_sent_as)) },
supportingContent = {
Text(
if(data.second === null) stringResource(R.string.unknown_sender)
else data.second!!.fullName()
)
}
)
ListItem(
headlineContent = { Text(stringResource(R.string.message_content)) },
supportingContent = { Text(log.payload) }
)
}
}
)
}
}
@@ -0,0 +1,43 @@
package ch.skew.remotrix.components
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Visibility
import androidx.compose.material.icons.filled.VisibilityOff
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation
import ch.skew.remotrix.R
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun PasswordField (
modifier: Modifier,
value: String,
onValueChange: (String) -> Unit,
visibility: Boolean,
toggleVisibility: () -> Unit,
enabled: Boolean
) {
TextField(
modifier = modifier,
value = value,
onValueChange = onValueChange,
label = { Text(stringResource(R.string.password)) },
singleLine = true,
visualTransformation = if (visibility) VisualTransformation.None else PasswordVisualTransformation(),
trailingIcon = {
IconButton(onClick = toggleVisibility) {
if (visibility) Icon(Icons.Filled.VisibilityOff, stringResource(R.string.hide_password))
else Icon(Icons.Filled.Visibility, stringResource(R.string.show_password))
}
},
enabled = enabled
)
}
@@ -0,0 +1,22 @@
package ch.skew.remotrix.components
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
@Composable
fun ScreenHelper(text: String){
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.fillMaxSize()
) {
Text(
text,
color = Color.Gray
)
}
}
@@ -0,0 +1,103 @@
package ch.skew.remotrix.components
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.selection.selectable
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.RadioButton
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import ch.skew.remotrix.R
import ch.skew.remotrix.classes.Account
@Composable
@Preview
fun SelectAccountDialogPreview(){
SelectAccountDialog(
accounts = listOf(Account(1, "temp", "matrix.org", "example.com", "!room:example.com", "!Example:example.com")),
close = {},
confirm = {},
title = "Please select an account",
noneChosenDesc = "Choose none",
show = true,
defaultSelected = 1
)
}
@Composable
fun SelectAccountDialog(
accounts: List<Account>,
close: () -> Unit,
confirm: (Int?) -> Unit,
title: String,
noneChosenDesc: String?,
show: Boolean,
defaultSelected: Int?
){
val chosen = remember { mutableStateOf(defaultSelected) }
if(show) {
AlertDialog(
onDismissRequest = close,
confirmButton = {
Button({ confirm(chosen.value) },
enabled = (noneChosenDesc === null && chosen.value !== null) || (noneChosenDesc !== null)
) {
Text(stringResource(R.string.choose))
}
},
dismissButton = {
Button(close){
Text(stringResource(R.string.cancel))
}
},
title = {
Text(title)
},
text = {
Column {
accounts.forEach {
@Suppress("IMPLICIT_BOXING_IN_IDENTITY_EQUALS")
LabelledRadioButton(it.fullName(), chosen.value !== null && it.id === chosen.value) {
chosen.value = it.id
}
}
if (noneChosenDesc !== null) Row(
Modifier
.fillMaxWidth()
.height(56.dp)
.selectable(
selected = chosen.value === null,
onClick = { chosen.value = null },
role = Role.RadioButton
)
.padding(horizontal = 16.dp),
verticalAlignment = Alignment.CenterVertically
) {
RadioButton(
selected = chosen.value === null,
onClick = null
)
Text(
text = noneChosenDesc,
style = MaterialTheme.typography.bodyLarge,
modifier = Modifier.padding(start = 16.dp)
)
}
}
}
)
}
}
@@ -0,0 +1,51 @@
package ch.skew.remotrix.components
import androidx.compose.foundation.layout.Column
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.res.stringResource
import ch.skew.remotrix.R
import ch.skew.remotrix.data.RemotrixSettings.OnSend
import ch.skew.remotrix.data.onSendToString
@Composable
fun SelectOnSendActionDialog(
close: () -> Unit,
confirm: (OnSend) -> Unit,
title: String,
show: Boolean,
defaultSelected: OnSend,
){
val chosen = remember { mutableStateOf(defaultSelected) }
if(show) {
AlertDialog(
onDismissRequest = close,
confirmButton = {
Button({ confirm(chosen.value) }) {
Text(stringResource(R.string.choose))
}
},
dismissButton = {
Button(close){
Text(stringResource(R.string.cancel))
}
},
title = {
Text(title)
},
text = {
Column {
arrayOf(OnSend.Thread, OnSend.React, OnSend.Reply, OnSend.None).forEach {
LabelledRadioButton(onSendToString(it), it == chosen.value) {
chosen.value = it
}
}
}
}
)
}
}
@@ -0,0 +1,96 @@
package ch.skew.remotrix.data
import android.content.ContentValues
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.migration.Migration
import ch.skew.remotrix.data.accountDB.AccountDao
import ch.skew.remotrix.data.accountDB.AccountData
import ch.skew.remotrix.data.debugLogDB.DebugLogDao
import ch.skew.remotrix.data.debugLogDB.DebugLogData
import ch.skew.remotrix.data.forwardRuleDB.ForwardRule
import ch.skew.remotrix.data.forwardRuleDB.ForwardRuleDao
import ch.skew.remotrix.data.logDB.LogDao
import ch.skew.remotrix.data.logDB.LogData
import ch.skew.remotrix.data.roomIdDB.RoomIdDao
import ch.skew.remotrix.data.roomIdDB.RoomIdData
@Database(
entities = [
AccountData::class,
ForwardRule::class,
RoomIdData::class,
LogData::class,
DebugLogData::class
],
version = 3
)
abstract class RemotrixDB: RoomDatabase(){
abstract fun getAccountDao(): AccountDao
abstract fun getForwardRuleDao(): ForwardRuleDao
abstract fun getRoomIdDao(): RoomIdDao
abstract fun getLogDao(): LogDao
abstract fun getDebugLogDao(): DebugLogDao
companion object {
@Volatile
private var instance: RemotrixDB? = null
fun getInstance(context: Context): RemotrixDB {
return instance ?: synchronized(this) {
instance ?: buildDatabase(context).also { instance = it }
}
}
private fun buildDatabase(context: Context) =
Room.databaseBuilder(context, RemotrixDB::class.java, "accounts.db")
.setJournalMode(androidx.room.RoomDatabase.JournalMode.WRITE_AHEAD_LOGGING)
.addMigrations(migration1To2)
.addMigrations(migration2To3)
.build()
private val migration2To3 = Migration(2, 3) {
it.execSQL(
"CREATE TABLE IF NOT EXISTS debug_log (" +
"id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT," +
"timestamp TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP," +
"error_msg TEXT NOT NULL," +
"payload TEXT" +
");"
)
}
private val migration1To2 = Migration(1, 2) {
it.execSQL(
"CREATE TABLE IF NOT EXISTS logs_temp (" +
"id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT," +
"timestamp TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP," +
"status TEXT NOT NULL," +
"error_msg TEXT," +
"msg_type TEXT NOT NULL," +
"forwarder_id INTEGER," +
"payload TEXT NOT NULL" +
");"
)
val cursor = it.query("SELECT * FROM logs")
cursor.move(1)
while(cursor.position < cursor.count){
val cv = ContentValues()
cv.put("id", cursor.getInt(0))
cv.put("timestamp", cursor.getString(1))
cv.put("status", cursor.getString(2))
cv.put("error_msg", cursor.getString(3))
cv.put("msg_type", if (cursor.getInt(4) == 1) "TestMessage" else "SMSForwarding")
cv.put("forwarder_id", cursor.getInt(5))
cv.put("payload", cursor.getString(6))
it.insert("logs_temp", SQLiteDatabase.CONFLICT_IGNORE, cv)
cursor.move(1)
}
it.execSQL("DROP TABLE IF EXISTS logs")
it.execSQL("ALTER TABLE logs_temp RENAME TO logs")
}
}
}
@@ -0,0 +1,173 @@
package ch.skew.remotrix.data
import android.content.Context
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
fun String.toOnSend(): RemotrixSettings.OnSend {
return when (this) {
"Thread" -> RemotrixSettings.OnSend.Thread
"React" -> RemotrixSettings.OnSend.React
"Reply" -> RemotrixSettings.OnSend.Reply
else -> RemotrixSettings.OnSend.None
}
}
fun onSendToString(onSend: RemotrixSettings.OnSend): String {
return when (onSend) {
RemotrixSettings.OnSend.Thread -> "Thread"
RemotrixSettings.OnSend.React -> "React"
RemotrixSettings.OnSend.Reply -> "Reply"
else -> "None"
}
}
class RemotrixSettings(
private val context: Context
) {
enum class OnSend {
Thread,
React,
Reply,
None
}
companion object {
private val Context.dataStore by preferencesDataStore(name = "settings")
val managerId = stringPreferencesKey("managerId")
val managementSpaceId = stringPreferencesKey("managementSpaceId")
val openedBefore = stringPreferencesKey("openedBefore")
val defaultForwarder = stringPreferencesKey("defaultForwarder")
val logging = stringPreferencesKey("logging")
val enableOnBootMessage = stringPreferencesKey("enableOnBootMessage")
val debugAlivePing = stringPreferencesKey("debugAlivePing")
val onSendSuccess = stringPreferencesKey("onSendSuccess")
val onSendFailure = stringPreferencesKey("onSendFailure")
val onErrorDebugLog = stringPreferencesKey("onSendFailure")
val backfillDone = stringPreferencesKey("backfillDone")
val backfillLimit = stringPreferencesKey("backfillLimit")
}
val getDebugAlivePing: Flow<Boolean> = context.dataStore.data.map { preferences ->
preferences[debugAlivePing] == "1"
}
val getOnSendSuccess: Flow<OnSend> = context.dataStore.data.map { preferences ->
(preferences[onSendSuccess]?.toOnSend() ?: OnSend.None)
}
val getOnSendFailure: Flow<OnSend> = context.dataStore.data.map { preferences ->
(preferences[onSendFailure]?.toOnSend() ?: OnSend.None)
}
val getManagerId: Flow<String> = context.dataStore.data.map { preferences ->
preferences[managerId] ?: ""
}
val getManagementSpaceId: Flow<String?> = context.dataStore.data.map { preferences ->
preferences[managementSpaceId]
}
val getOpenedBefore: Flow<Boolean> = context.dataStore.data.map { preferences ->
preferences[openedBefore] == "1"
}
val getDefaultForwarder: Flow<Int> = context.dataStore.data.map { preferences ->
preferences[defaultForwarder]?.toInt() ?: -1
}
val getLogging: Flow<Boolean> = context.dataStore.data.map { preferences ->
preferences[logging] == "1"
}
val getEnableOnBootMessage: Flow<Boolean> = context.dataStore.data.map { preferences ->
preferences[enableOnBootMessage] === null || preferences[enableOnBootMessage] != "0"
}
val getOnErrorDebugLog: Flow<Boolean> = context.dataStore.data.map { preferences ->
preferences[onErrorDebugLog] == "1"
}
val getBackfillDone: Flow<Boolean> = context.dataStore.data.map { preferences ->
preferences[backfillDone] == "1"
}
val getBackfillLimit: Flow<Int> = context.dataStore.data.map { preferences ->
preferences[backfillLimit]?.toInt() ?: 100
}
suspend fun saveOnSendSuccess(set: OnSend) {
context.dataStore.edit { preferences ->
preferences[onSendSuccess] = onSendToString(set)
}
}
suspend fun saveOnSendFailure(set: OnSend) {
context.dataStore.edit { preferences ->
preferences[onSendFailure] = onSendToString(set)
}
}
suspend fun saveManagerId(name: String) {
context.dataStore.edit { preferences ->
preferences[managerId] = name
}
}
suspend fun saveManagementSpaceId(id: String?) {
context.dataStore.edit { preferences ->
if (id === null) preferences.remove(managementSpaceId)
else preferences[managementSpaceId] = id
}
}
suspend fun saveOpenedBefore() {
context.dataStore.edit { preferences ->
preferences[openedBefore] = "1"
}
}
suspend fun saveDefaultForwarder(id: Int?){
context.dataStore.edit { preferences ->
if(id === null) preferences.remove(defaultForwarder)
else preferences[defaultForwarder] = id.toString()
}
}
suspend fun saveLogging(set: Boolean) {
context.dataStore.edit { preferences ->
preferences[logging] = if(set) "1" else "0"
}
}
suspend fun saveEnableOnBootMessage(set: Boolean) {
context.dataStore.edit { preferences ->
preferences[enableOnBootMessage] = if (set) "1" else "0"
}
}
suspend fun saveDebugAlivePing(set: Boolean) {
context.dataStore.edit { preferences ->
preferences[debugAlivePing] = if (set) "1" else "0"
}
}
suspend fun saveOnErrorDebugLog(set: Boolean) {
context.dataStore.edit { preferences ->
preferences[onErrorDebugLog] = if(set) "1" else "0"
}
}
suspend fun saveBackfillDone(set: Boolean) {
context.dataStore.edit { preferences ->
preferences[backfillDone] = if (set) "1" else "0"
}
}
suspend fun saveBackfillLimit(limit: Int) {
context.dataStore.edit { preferences ->
preferences[backfillLimit] = limit.toString()
}
}
}
@@ -0,0 +1,23 @@
package ch.skew.remotrix.data.accountDB
import androidx.room.Dao
import androidx.room.Query
import kotlinx.coroutines.flow.Flow
@Dao
interface AccountDao{
@Query("INSERT INTO accounts (user_id, base_url) VALUES (:userId, :baseUrl)")
suspend fun insert(userId: String, baseUrl: String): Long
@Query("SELECT message_space FROM accounts WHERE id = :id")
suspend fun getMessageSpace(id: Int): String
@Query("DELETE FROM accounts WHERE id = :id")
suspend fun delete(id: Int): Int
@Query("SELECT * FROM accounts WHERE domain NOT NULL")
fun getAllAccounts(): Flow<List<AccountData>>
@Query("SELECT * FROM accounts WHERE id = :id AND domain NOT NULL")
fun getAccountById(id: Int): Flow<List<AccountData>>
@Query("SELECT * FROM accounts WHERE user_id = :user_id AND domain NOT NULL LIMIT 1")
fun getAccountByUserId(user_id: String): Flow<List<AccountData>>
@Query("UPDATE accounts SET domain = :domain, management_room = :managementRoom, message_space = :messagingSpace WHERE id = :accountId")
suspend fun activateAccount(accountId: Long, domain: String, managementRoom: String, messagingSpace: String): Int
}
@@ -0,0 +1,21 @@
package ch.skew.remotrix.data.accountDB
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "accounts")
data class AccountData(
@PrimaryKey(autoGenerate = true)
val id: Int,
@ColumnInfo(name = "user_id")
val userId: String,
@ColumnInfo(name = "domain")
val domain: String?,
@ColumnInfo(name = "base_url")
val baseUrl: String,
@ColumnInfo(name = "management_room")
val managementRoom: String?,
@ColumnInfo(name = "message_space")
val messageSpace: String?
)
@@ -0,0 +1,13 @@
package ch.skew.remotrix.data.accountDB
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.stateIn
class AccountViewModel(
private val dao: AccountDao
): ViewModel() {
val accounts = dao.getAllAccounts().stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), emptyList())
}
@@ -0,0 +1,21 @@
package ch.skew.remotrix.data.debugLogDB
import androidx.room.Dao
import androidx.room.Query
import ch.skew.remotrix.classes.MsgStatus
import ch.skew.remotrix.classes.MsgType
import kotlinx.coroutines.flow.Flow
@Dao
interface DebugLogDao{
/// Write a log entry into the database
@Query("INSERT INTO debug_log (error_msg, payload) VALUES (:errorMsg, :payload)")
suspend fun addLog(errorMsg: String, payload: String? = null): Long
@Query("SELECT * FROM debug_log ORDER BY timestamp DESC")
fun getLogs(): Flow<List<DebugLogData>>
@Query("DELETE FROM debug_log")
suspend fun deleteAll(): Int
}
@@ -0,0 +1,28 @@
package ch.skew.remotrix.data.debugLogDB
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import ch.skew.remotrix.classes.MsgStatus
import ch.skew.remotrix.classes.MsgType
/**
* Database for storing errors that have occurred when the messages are either sent or received
* Stores issues that have occurred only, successful transmissions should never be stored
* TODO: Perhaps make it opt-in to store successful transmissions too?
*/
@Entity(tableName = "debug_log")
data class DebugLogData(
@PrimaryKey(autoGenerate = true)
val id: Int,
@ColumnInfo(name = "timestamp", defaultValue = "CURRENT_TIMESTAMP")
val timestamp: String,
@ColumnInfo(name = "error_msg")
val errorMsg: String,
/**
* The data that is supposed to be sent
* This is nullable because storing user information is opt-in
*/
@ColumnInfo(name = "payload")
val payload: String?
)
@@ -0,0 +1,13 @@
package ch.skew.remotrix.data.debugLogDB
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.stateIn
class DebugLogViewModel(
private val dao: DebugLogDao
): ViewModel() {
val debugLog = dao.getLogs().stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), emptyList())
}
@@ -0,0 +1,51 @@
package ch.skew.remotrix.data.forwardRuleDB
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.ForeignKey
import androidx.room.PrimaryKey
import ch.skew.remotrix.data.accountDB.AccountData
/**
* Determines where messages should be sent to upon receiving messages via SMS.
* TODO: Make it bidirectional (Currently only supports SMS -> Matrix only)
*/
@Entity(
tableName = "forward_rule",
foreignKeys = [
ForeignKey(
entity = AccountData::class,
parentColumns = arrayOf("id"),
childColumns = arrayOf("forwarder_id"),
onDelete = ForeignKey.CASCADE
)
]
)
data class ForwardRule(
/**
* Account that will be used for sending messages via Matrix
* Obviously will be foreign key
*/
@ColumnInfo(name = "forwarder_id", index = true)
val forwarderId: Int,
/**
* Regex that gets testes against the phone number of the sender
*/
@ColumnInfo(name = "sender_regex")
val senderRegex: String,
/**
* Regex that gets testes against the body of the message
*/
@ColumnInfo(name = "body_regex")
val bodyRegex: String,
/**
* Priority: Lower means tested against first
*/
@ColumnInfo(name = "priority", index = true)
val priority: Int,
/**
* ID of this send action
*/
@PrimaryKey(autoGenerate = true)
val id: Long,
)
@@ -0,0 +1,14 @@
package ch.skew.remotrix.data.forwardRuleDB
import androidx.room.Dao
import androidx.room.Query
import kotlinx.coroutines.flow.Flow
@Dao
interface ForwardRuleDao{
@Query("SELECT * FROM forward_rule")
fun getAllAsFlow(): Flow<List<ForwardRule>>
@Query("SELECT * FROM forward_rule")
fun getAll(): List<ForwardRule>
}
@@ -0,0 +1,12 @@
package ch.skew.remotrix.data.forwardRuleDB
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.stateIn
class ForwardRuleViewModel(
private val dao: ForwardRuleDao
): ViewModel() {
val forwardRule = dao.getAllAsFlow().stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), emptyList())
}
@@ -0,0 +1,22 @@
Accounts will be held in "accounts" database.
When a message arrives from SMS to Matrix, the following info are available to this app, and are used in choosing the destination space/room and Matrix sender.
- Content (Matches regex)
- Sender name (Matches regex)
Instead of implementing additional conditions, there will be regex helpers.
RoomID contains the following:
- SMS sender phone number
- Room ID
- Account ID
This is automatically generated for every unique pair of Account ID and SMS phone number.
SendAction has been greatly simplified. SendAction contains the following:
- SMS sender regex
- SMS body regex
- Priority
- Account ID (may be null)
- ID
If SMS sender and body regex matches, the account associated with the account ID will be used to send the message via Matrix.
Room to send this message is determined by roomId table.
If Account ID is null, message is not forwarded.
@@ -0,0 +1,25 @@
package ch.skew.remotrix.data.logDB
import androidx.room.Dao
import androidx.room.Query
import ch.skew.remotrix.classes.MsgStatus
import ch.skew.remotrix.classes.MsgType
import kotlinx.coroutines.flow.Flow
@Dao
interface LogDao{
/// Write a log entry into the database
@Query("INSERT INTO logs (status, msg_type, payload) VALUES (:defStatus, :msgType, :payload)")
suspend fun writeAhead(msgType: MsgType, payload: String, defStatus: MsgStatus = MsgStatus.MESSAGE_SENDING_FAILED): Long
@Query("UPDATE logs SET status = :status, error_msg = :errorMsg, forwarder_id = :forwarderId WHERE id = :id")
suspend fun setFailure(id: Long, status: MsgStatus, errorMsg: String?, forwarderId: Int?): Int
@Query("UPDATE logs SET status = :status, forwarder_id = :forwarderId WHERE id = :id")
suspend fun setSuccess(id: Long, status: MsgStatus, forwarderId: Int?): Int
@Query("SELECT * FROM logs ORDER BY timestamp DESC")
fun getLogs(): Flow<List<LogData>>
@Query("DELETE FROM logs")
suspend fun deleteAll(): Int
}
@@ -0,0 +1,25 @@
package ch.skew.remotrix.data.logDB
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import ch.skew.remotrix.classes.MsgStatus
import ch.skew.remotrix.classes.MsgType
@Entity(tableName = "logs")
data class LogData(
@PrimaryKey(autoGenerate = true)
val id: Int,
@ColumnInfo(name = "timestamp", defaultValue = "CURRENT_TIMESTAMP")
val timestamp: String,
@ColumnInfo(name = "status")
val status: MsgStatus,
@ColumnInfo(name = "error_msg")
val errorMsg: String?,
@ColumnInfo(name = "msg_type")
val msgType: MsgType,
@ColumnInfo(name = "forwarder_id")
val forwarderId: Int?,
@ColumnInfo(name = "payload")
val payload: String
)
@@ -0,0 +1,13 @@
package ch.skew.remotrix.data.logDB
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.stateIn
class LogViewModel(
private val dao: LogDao
): ViewModel() {
val logs = dao.getLogs().stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), emptyList())
}
@@ -0,0 +1,23 @@
package ch.skew.remotrix.data.roomIdDB
import androidx.room.Dao
import androidx.room.Query
import androidx.room.Upsert
@Dao
interface RoomIdDao{
@Upsert
suspend fun insert(roomIdData: RoomIdData): Long
/// Given a phone humber, get the corresponding room ID
@Query("SELECT room_id FROM room_ids WHERE phone_number = :phoneNumber AND forwarder_id = :forwarderId")
suspend fun getDestRoom(phoneNumber: String, forwarderId: Int): String?
/// 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?
/// Delete a room given a room ID
@Query("DELETE FROM room_ids WHERE room_id = :roomId")
suspend fun delRoomById(roomId: String): Int
}
@@ -0,0 +1,27 @@
package ch.skew.remotrix.data.roomIdDB
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.ForeignKey
import ch.skew.remotrix.data.accountDB.AccountData
@Entity(
tableName = "room_ids",
primaryKeys = ["phone_number", "forwarder_id"],
foreignKeys = [
ForeignKey(
entity = AccountData::class,
parentColumns = arrayOf("id"),
childColumns = arrayOf("forwarder_id"),
onDelete = ForeignKey.CASCADE
)
]
)
data class RoomIdData(
@ColumnInfo(name = "phone_number")
val phoneNumber: String,
@ColumnInfo(name = "forwarder_id", index = true)
val senderId: Int,
@ColumnInfo(name = "room_id")
val roomId: String
)
@@ -0,0 +1,33 @@
package ch.skew.remotrix.receiver
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.work.Constraints
import androidx.work.ExistingPeriodicWorkPolicy
import androidx.work.NetworkType
import androidx.work.PeriodicWorkRequestBuilder
import androidx.work.WorkManager
import ch.skew.remotrix.background.ServiceWatcher
import java.time.Duration
class OnBoot : BroadcastReceiver(){
@RequiresApi(Build.VERSION_CODES.O)
override fun onReceive(context: Context?, intent: Intent?) {
if(intent?.action.equals(Intent.ACTION_BOOT_COMPLETED)){
if(context == null) return
val work = PeriodicWorkRequestBuilder<ServiceWatcher>(Duration.ofHours(1))
.setConstraints(
Constraints.Builder()
.setRequiredNetworkType(
NetworkType.CONNECTED
).build()
)
.build()
val workManager = WorkManager.getInstance(context)
workManager.enqueueUniquePeriodicWork("service_watcher", ExistingPeriodicWorkPolicy.KEEP, work)
}
}
}
@@ -0,0 +1,30 @@
package ch.skew.remotrix.receiver
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.provider.Telephony
import ch.skew.remotrix.background.CommandService
class OnSMS : BroadcastReceiver(){
override fun onReceive(context: Context?, intent: Intent?) {
if(intent?.action.equals("android.provider.Telephony.SMS_RECEIVED")){
if(context == null) return
val msgs = Telephony.Sms.Intents.getMessagesFromIntent(intent)
val msgList = mutableListOf<String>()
val sender = msgs[0].originatingAddress
if (sender === null) return
// Apparently, there may be msgs[1], but this is only when the message is an MMS, content being longer than a single SMS.
msgs.forEach {
msgList.add(it.messageBody)
}
Intent(context, CommandService::class.java)
.putExtra(CommandService.SENDER, sender)
.putExtra(CommandService.PAYLOAD, msgList.joinToString(""))
.apply {
action = CommandService.SEND_MSG
context.startService(this)
}
}
}
}
@@ -0,0 +1,93 @@
package ch.skew.remotrix.settings
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.Error
import androidx.compose.material.icons.filled.Schedule
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.ListItem
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import ch.skew.remotrix.R
import ch.skew.remotrix.data.RemotrixSettings
import kotlinx.coroutines.launch
@Preview
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun DebugSettings(
goBack: () -> Unit = {},
debugAlivePing: Boolean = false,
onErrorDebugLog: Boolean = false
) {
val scope = rememberCoroutineScope()
val context = LocalContext.current
val settings = RemotrixSettings(context)
Scaffold(
topBar = {
TopAppBar({
Text(stringResource(R.string.debug_settings))
}, navigationIcon = {
IconButton(goBack) {
Icon(Icons.Filled.ArrowBack, stringResource(R.string.go_back))
}
})
},
) { padding ->
val scroll = rememberScrollState()
Column(
modifier = Modifier
.padding(padding)
.verticalScroll(scroll)
) {
ListItem(
headlineContent = { Text(stringResource(R.string.receive_message_on_service_check)) },
supportingContent = { Text(stringResource(R.string.receive_message_on_service_check_desc)) },
leadingContent = {
Icon(
Icons.Filled.Schedule,
contentDescription = stringResource(R.string.receive_message_on_service_check)
)
},
modifier = Modifier.clickable {
scope.launch { settings.saveDebugAlivePing(!debugAlivePing) }
},
trailingContent = {
Switch(checked = debugAlivePing, onCheckedChange = null)
}
)
ListItem(
headlineContent = { Text(stringResource(R.string.log_matrix_client_errors)) },
supportingContent = { Text(stringResource(R.string.log_matrix_client_errors_desc)) },
leadingContent = {
Icon(
Icons.Filled.Error,
contentDescription = stringResource(R.string.log_matrix_client_errors)
)
},
modifier = Modifier.clickable {
scope.launch { settings.saveOnErrorDebugLog(!onErrorDebugLog) }
},
trailingContent = {
Switch(checked = onErrorDebugLog, onCheckedChange = null)
}
)
}
}
}
@@ -0,0 +1,232 @@
package ch.skew.remotrix.settings
import android.widget.Toast
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Announcement
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.AccountCircle
import androidx.compose.material.icons.filled.BugReport
import androidx.compose.material.icons.filled.ChatBubble
import androidx.compose.material.icons.filled.DeleteForever
import androidx.compose.material.icons.filled.Start
import androidx.compose.material.icons.filled.Storage
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.ListItem
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import ch.skew.remotrix.R
import ch.skew.remotrix.classes.Account
import ch.skew.remotrix.components.ListHeader
import ch.skew.remotrix.components.SelectAccountDialog
import ch.skew.remotrix.components.SelectOnSendActionDialog
import ch.skew.remotrix.data.RemotrixDB
import ch.skew.remotrix.data.RemotrixSettings
import kotlinx.coroutines.launch
enum class CurrentDialog {
None,
SelectAccount,
OnSendSuccess,
OnSendFailure
}
@Preview
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun Settings(
accounts: List<Account> = listOf(),
defaultForwarder: Int = -1,
logging: Boolean = true,
enableOnBootMessage: Boolean = true,
goBack: () -> Unit = {},
debugMenu: () -> Unit = {},
onSendSuccess: RemotrixSettings.OnSend = RemotrixSettings.OnSend.None,
onSendFailure: RemotrixSettings.OnSend = RemotrixSettings.OnSend.None,
) {
val open = remember { mutableStateOf(CurrentDialog.None) }
val scope = rememberCoroutineScope()
val context = LocalContext.current
val settings = RemotrixSettings(context)
Scaffold(
topBar = {
TopAppBar({
Text(stringResource(R.string.settings))
}, navigationIcon = {
IconButton(goBack) {
Icon(Icons.Filled.ArrowBack, stringResource(R.string.go_back))
}
})
},
) { padding ->
val scroll = rememberScrollState()
Column(
modifier = Modifier
.padding(padding)
.verticalScroll(scroll)
) {
ListHeader(stringResource(R.string.accounts))
ListItem(
headlineContent = { Text(stringResource(R.string.choose_default_account)) },
supportingContent = { Text(stringResource(R.string.choose_default_account_desc)) },
leadingContent = {
Icon(
Icons.Filled.AccountCircle,
contentDescription = stringResource(R.string.choose_default_account)
)
},
modifier = Modifier.clickable { open.value = CurrentDialog.SelectAccount }
)
ListItem(
headlineContent = { Text(stringResource(R.string.enable_service_ready_message)) },
supportingContent = { Text(stringResource(R.string.enable_service_ready_message_desc)) },
leadingContent = {
Icon(
Icons.Filled.Start,
contentDescription = stringResource(R.string.enable_service_ready_message)
)
},
modifier = Modifier.clickable {
scope.launch {
settings.saveEnableOnBootMessage(!enableOnBootMessage)
}
},
trailingContent = {
Switch(checked = enableOnBootMessage, onCheckedChange = null)
}
)
ListHeader(stringResource(R.string.behaviour))
ListItem(
headlineContent = { Text("Successful Message Transmission") },
supportingContent = {
Text("Determine what happens if the SMS is sent successfully.")
Text("Commands are not affected by this.")
},
leadingContent = {
Icon(
Icons.Filled.ChatBubble,
contentDescription = "Successful Message Transmission"
)
},
modifier = Modifier.clickable { open.value = CurrentDialog.OnSendSuccess }
)
ListItem(
headlineContent = { Text("Unsuccessful Message Transmission") },
supportingContent = {
Text("Determine what happens if sending SMS fails.")
Text("Commands are not affected by this.")
},
leadingContent = {
Icon(
Icons.Filled.Announcement,
contentDescription = "Unsuccessful Message Transmission"
)
},
modifier = Modifier.clickable { open.value = CurrentDialog.OnSendFailure }
)
ListHeader(stringResource(R.string.logging))
ListItem(
headlineContent = { Text(stringResource(R.string.enable_logging)) },
supportingContent = { Text(stringResource(R.string.enable_logging_desc)) },
leadingContent = {
Icon(
Icons.Filled.Storage,
contentDescription = stringResource(R.string.enable_logging)
)
},
modifier = Modifier.clickable {
scope.launch {
settings.saveLogging(!logging)
}
},
trailingContent = {
Switch(checked = logging, onCheckedChange = null)
}
)
ListItem(
headlineContent = { Text(stringResource(R.string.delete_log)) },
supportingContent = { Text(stringResource(R.string.delete_log_desc)) },
leadingContent = {
Icon(
Icons.Filled.DeleteForever,
contentDescription = stringResource(R.string.delete_log)
)
},
modifier = Modifier.clickable {
Toast.makeText(
context,
context.getString(R.string.log_deleted),
Toast.LENGTH_SHORT
).show()
scope.launch { RemotrixDB.getInstance(context).getLogDao().deleteAll() }
}
)
ListHeader(stringResource(R.string.debug))
ListItem(
headlineContent = { Text(stringResource(R.string.debug_menu)) },
supportingContent = { Text(stringResource(R.string.debug_menu_desc)) },
leadingContent = {
Icon(
Icons.Filled.BugReport,
contentDescription = stringResource(R.string.debug_menu)
)
},
modifier = Modifier.clickable { debugMenu() }
)
}
}
SelectAccountDialog(
accounts = accounts,
close = { open.value = CurrentDialog.None },
confirm = {
scope.launch {
settings.saveDefaultForwarder(it)
}
open.value = CurrentDialog.None
},
title = stringResource(R.string.choose_default_account),
noneChosenDesc = stringResource(R.string.none_option),
show = open.value == CurrentDialog.SelectAccount,
defaultSelected = if (defaultForwarder == -1) null else defaultForwarder
)
SelectOnSendActionDialog(
close = { open.value = CurrentDialog.None },
confirm = {
if (open.value == CurrentDialog.OnSendSuccess) {
scope.launch {
settings.saveOnSendSuccess(it)
}
} else if (open.value == CurrentDialog.OnSendFailure) {
scope.launch {
settings.saveOnSendFailure(it)
}
}
open.value = CurrentDialog.None
},
title = if (open.value == CurrentDialog.OnSendSuccess) "Select action on success" else "Select action on failure",
show = open.value == CurrentDialog.OnSendSuccess || open.value == CurrentDialog.OnSendFailure,
defaultSelected = if (open.value == CurrentDialog.OnSendSuccess) {
onSendSuccess
} else {
onSendFailure
}
)
}
@@ -0,0 +1,81 @@
package ch.skew.remotrix.setup
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ListItem
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.unit.dp
import ch.skew.remotrix.data.RemotrixSettings
import kotlinx.coroutines.launch
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AdditionalInfo(
nextPage: () -> Unit
){
Scaffold(
topBar = {
TopAppBar({
Text("Setup Complete!")
})
}
) { padding ->
val settings = RemotrixSettings(LocalContext.current)
val scope = rememberCoroutineScope()
val scroll = rememberScrollState()
Column(
modifier = Modifier
.padding(padding)
.fillMaxWidth()
.verticalScroll(scroll),
verticalArrangement = Arrangement.spacedBy(10.dp)
) {
ListItem(
headlineContent = { Text("Now what?") },
supportingContent = {
Text("Basic setup is now complete.")
Text(
buildAnnotatedString {
append("You must set at least one ")
withStyle(style = SpanStyle(fontWeight = FontWeight.Bold)) {
append("bot account")
}
append(" to forward the messages, and set it as default account in the settings. ")
withStyle(style = SpanStyle(fontWeight = FontWeight.Bold)) {
append("Default forwarder bot is not set by default, meaning if you do not set it, messages will not be forwarded!")
}
}
)
Text("Once you complete these two, you should now have messages forwarded to you.")
}
)
Button(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 10.dp),
onClick = {
scope.launch { settings.saveOpenedBefore() }
nextPage()
}
) {
Text("Done")
}
}
}
}
@@ -0,0 +1,257 @@
package ch.skew.remotrix.setup
import android.Manifest
import android.annotation.SuppressLint
import android.content.Context.POWER_SERVICE
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.PowerManager
import android.provider.Settings
import android.widget.Toast
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.RequiresApi
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ListItem
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.core.content.ContextCompat
import androidx.core.content.ContextCompat.startActivity
enum class CurrentlyGranting {
Notification,
ReceiveSMS,
SendSMS,
Battery,
Contacts
}
@SuppressLint("BatteryLife")
@RequiresApi(Build.VERSION_CODES.TIRAMISU)
@OptIn(ExperimentalMaterial3Api::class)
@Composable
@Preview
fun AskPermissions(
nextPage: () -> Unit = {}
){
Scaffold(
topBar = {
TopAppBar({
Text("Permissions")
})
}
) { padding ->
val context = LocalContext.current
val packageName = context.packageName
val pm = context.getSystemService(POWER_SERVICE) as PowerManager
val currentlyGranting = remember { mutableStateOf<CurrentlyGranting?>(null) }
val notificationGranted = remember {
mutableStateOf(
ContextCompat.checkSelfPermission(
context,
Manifest.permission.POST_NOTIFICATIONS
) == PackageManager.PERMISSION_GRANTED
)
}
val smsSendingGranted = remember {
mutableStateOf(
ContextCompat.checkSelfPermission(
context,
Manifest.permission.SEND_SMS
) == PackageManager.PERMISSION_GRANTED
)
}
val smsReceivingGranted = remember {
mutableStateOf(
ContextCompat.checkSelfPermission(
context,
Manifest.permission.RECEIVE_MMS
) == PackageManager.PERMISSION_GRANTED
)
}
val contactsGranted = remember {
mutableStateOf(
ContextCompat.checkSelfPermission(
context,
Manifest.permission.READ_CONTACTS
) == PackageManager.PERMISSION_GRANTED
)
}
val batteryGranted = remember {
mutableStateOf(pm.isIgnoringBatteryOptimizations(packageName))
}
val dialogMsg = remember { mutableStateOf("") }
val showDialog = remember { mutableStateOf(false) }
val launcher = rememberLauncherForActivityResult(
ActivityResultContracts.RequestPermission()
) { isGranted ->
println(isGranted)
if (isGranted) {
when(currentlyGranting.value) {
CurrentlyGranting.Contacts -> contactsGranted.value = true
CurrentlyGranting.Notification -> notificationGranted.value = true
CurrentlyGranting.ReceiveSMS -> smsReceivingGranted.value = true
CurrentlyGranting.SendSMS -> smsSendingGranted.value = true
CurrentlyGranting.Battery -> batteryGranted.value = true
null -> {}
}
Toast.makeText(
context,
"Permission granted.",
Toast.LENGTH_SHORT
).show()
} else {
Toast.makeText(
context,
"Permission denied.",
Toast.LENGTH_SHORT
).show()
}
}
val scroll = rememberScrollState()
Column(
modifier = Modifier
.padding(padding)
.fillMaxWidth()
.verticalScroll(scroll),
verticalArrangement = Arrangement.spacedBy(10.dp)
) {
ListItem(
headlineContent = { Text("Required Permissions") },
supportingContent = {
Text(
buildAnnotatedString {
append("These permissions are ")
withStyle(style = SpanStyle(fontWeight = FontWeight.Bold)) {
append("required")
}
append(", meaning the app will not be able to perform its function without them.")
}
)
}
)
PermissionItem(
name = "Notification",
granted = notificationGranted.value,
onClick = {
currentlyGranting.value = CurrentlyGranting.Notification
launcher.launch(Manifest.permission.POST_NOTIFICATIONS)
},
onInfoClick = {
dialogMsg.value = "Notification is used for showing you the current status of the critical background service."
showDialog.value = true
}
)
PermissionItem(
name = "Receive SMS",
granted = smsReceivingGranted.value,
onClick = {
currentlyGranting.value = CurrentlyGranting.ReceiveSMS
launcher.launch(Manifest.permission.RECEIVE_SMS)
},
onInfoClick = {
dialogMsg.value = "App needs to be able to receive SMS to forward them over Matrix."
showDialog.value = true
}
)
PermissionItem(
name = "Send SMS",
granted = smsSendingGranted.value,
onClick = {
currentlyGranting.value = CurrentlyGranting.SendSMS
launcher.launch(Manifest.permission.SEND_SMS)
},
onInfoClick = {
dialogMsg.value = "App needs to be able to send SMS to forward messages from Matrix over SMS."
showDialog.value = true
}
)
PermissionItem(
name = "Bypass battery optimisation",
granted = batteryGranted.value,
onClick = {
val intent = Intent()
intent.action = Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS
intent.data = Uri.parse("package:$packageName")
startActivity(context, intent, null)
batteryGranted.value = true
},
onInfoClick = {
dialogMsg.value = "Service needs to be kept running so that bridging feature doesn't get deactivated randomly."
showDialog.value = true
}
)
ListItem(
headlineContent = { Text("Optional Permissions") },
supportingContent = {
Text(
buildAnnotatedString {
append("These permissions are ")
withStyle(style = SpanStyle(fontWeight = FontWeight.Bold)) {
append("not required")
}
append(", and this app can function without them.")
}
)
}
)
PermissionItem(
name = "Read contacts",
granted = contactsGranted.value,
onClick = {
currentlyGranting.value = CurrentlyGranting.Contacts
launcher.launch(Manifest.permission.READ_CONTACTS)
},
onInfoClick = {
dialogMsg.value = "Contact information is used for new messaging room names. App still works without this permission, but the room name will always be phone number, even if you have them saved in your contacts list."
showDialog.value = true
}
)
if(showDialog.value) {
AlertDialog(
onDismissRequest = { showDialog.value = false },
title = {
Text("Permission Description")
},
text = { Text(dialogMsg.value) },
confirmButton = {
Button({ showDialog.value = false }){
Text("Close")
}
}
)
}
Button(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 10.dp),
onClick = nextPage,
enabled = smsSendingGranted.value && smsReceivingGranted.value && notificationGranted.value && batteryGranted.value
) {
Text("Next")
}
}
}
}
@@ -0,0 +1,50 @@
package ch.skew.remotrix.setup
import androidx.compose.foundation.clickable
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.CheckBox
import androidx.compose.material.icons.filled.CheckBoxOutlineBlank
import androidx.compose.material.icons.filled.Info
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.ListItem
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
@Composable
@Preview
fun PermissionItemPreview() {
PermissionItem("Permission", true, {}, {})
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun PermissionItem(
name: String,
granted: Boolean,
onClick: () -> Unit,
onInfoClick: () -> Unit
) {
ListItem(
headlineContent = { Text(name) },
leadingContent = {
if(granted) Icon(
Icons.Filled.CheckBox,
contentDescription = "Permission granted",
)
else Icon(
Icons.Filled.CheckBoxOutlineBlank,
contentDescription = "Permission not granted"
)
},
modifier = Modifier.clickable(onClick = onClick),
trailingContent = {
IconButton(onInfoClick) {
Icon(Icons.Filled.Info, contentDescription = "Permission description")
}
}
)
}
@@ -0,0 +1,140 @@
package ch.skew.remotrix.setup
import android.content.Context
import android.widget.Toast
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ListItem
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.unit.dp
import ch.skew.remotrix.data.RemotrixSettings
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SetManagementSpace(
nextPage: () -> Unit
){
Scaffold(
topBar = {
TopAppBar({
Text("Set Management Space")
})
}
) { padding ->
val managementSpace = remember { mutableStateOf("") }
val context = LocalContext.current
val scope = rememberCoroutineScope()
val settings = RemotrixSettings(context)
val currentManagementSpace = settings.getManagementSpaceId.collectAsState(initial = "")
val scroll = rememberScrollState()
Column(
modifier = Modifier
.padding(padding)
.fillMaxWidth()
.verticalScroll(scroll),
verticalArrangement = Arrangement.spacedBy(10.dp)
) {
ListItem(
headlineContent = { Text("Management Space") },
supportingContent = {
Text(
buildAnnotatedString {
append("Upon adding a ")
withStyle(style = SpanStyle(fontWeight = FontWeight.Bold)) {
append("bot account")
}
append(" to this app, it will automatically create a ")
withStyle(style = SpanStyle(fontWeight = FontWeight.Bold)) {
append("management room")
}
append(" and invite the ")
withStyle(style = SpanStyle(fontWeight = FontWeight.Bold)) {
append("manager account")
}
append(". If you are planning on adding multiple accounts, it may be desirable to have all the rooms under a single space.")
}
)
Text(
buildAnnotatedString {
append("If not, you may leave this field empty. Regardless of whether ")
withStyle(style = SpanStyle(fontWeight = FontWeight.Bold)) {
append("management space")
}
append(" is set or not, management rooms will still be created for each account on this app.")
}
)
if (currentManagementSpace.value !== "") Text(
buildAnnotatedString {
append("You already have set a ")
withStyle(style = SpanStyle(fontWeight = FontWeight.Bold)) {
append("management space")
}
append(". Press continue to keep current settings.")
}
)
}
)
TextField(
value = managementSpace.value,
onValueChange = { managementSpace.value = it },
label = { Text("Space ID") },
singleLine = true,
placeholder = { Text(
if (currentManagementSpace.value === null
|| currentManagementSpace.value === "")
"!spaceId:example.com"
else currentManagementSpace.value!!
) },
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 10.dp)
)
Button(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 10.dp),
onClick = {
if (managementSpace.value === "" && currentManagementSpace.value !== "") nextPage()
else confirmSpace(managementSpace.value, context, scope, settings, nextPage)
}
) {
Text("Continue")
}
}
}
}
fun confirmSpace(managementSpace: String, context: Context, scope: CoroutineScope, settings: RemotrixSettings, done: () -> Unit){
val spacePattern = Regex("!.+:[A-z0-9\\.-]+")
if(managementSpace !== "" && spacePattern.matchEntire(managementSpace) === null){
Toast.makeText(context, "The space ID you have entered is invalid.", Toast.LENGTH_SHORT).show()
return
}
scope.launch {
settings.saveManagementSpaceId(if (managementSpace === "") null else managementSpace)
Toast.makeText(context, "Management space ID set.", Toast.LENGTH_SHORT).show()
done()
}
}
@@ -0,0 +1,137 @@
package ch.skew.remotrix.setup
import android.content.Context
import android.widget.Toast
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ListItem
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.unit.dp
import ch.skew.remotrix.data.RemotrixSettings
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SetManagerAccount(
nextPage: () -> Unit
){
Scaffold(
topBar = {
TopAppBar({
Text("Set Manager Account")
})
}
) { padding ->
val mgrId = remember { mutableStateOf("") }
val context = LocalContext.current
val scope = rememberCoroutineScope()
val settings = RemotrixSettings(context)
val currentMgrId = settings.getManagerId.collectAsState(initial = "")
val scroll = rememberScrollState()
Column(
modifier = Modifier
.padding(padding)
.fillMaxWidth()
.verticalScroll(scroll),
verticalArrangement = Arrangement.spacedBy(10.dp)
) {
ListItem(
headlineContent = { Text("Manager Account") },
supportingContent = {
Text(
buildAnnotatedString {
withStyle(style = SpanStyle(fontWeight = FontWeight.Bold)) {
append("Manager account")
}
append(" is the account that gets automatically invited into all rooms registered bots generate, which includes all message forwarding rooms and management rooms.")
}
)
Text(
buildAnnotatedString {
append("Essentially, ")
withStyle(style = SpanStyle(fontWeight = FontWeight.Bold)) {
append("manager account")
}
append(" is the first to receive any forwarded messages.")
}
)
Text(
buildAnnotatedString {
append("Please enter the username of the ")
withStyle(style = SpanStyle(fontWeight = FontWeight.Bold)) {
append("manager account")
}
append(" here.")
}
)
if (currentMgrId.value !== "") Text(
buildAnnotatedString {
append("You already have set a ")
withStyle(style = SpanStyle(fontWeight = FontWeight.Bold)) {
append("manager account")
}
append(". Press continue to keep current settings.")
}
)
}
)
TextField(
value = mgrId.value,
onValueChange = { mgrId.value = it },
label = { Text("Manager ID") },
singleLine = true,
placeholder = { Text(if(currentMgrId.value === "") "@username:example.com" else currentMgrId.value) },
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 10.dp)
)
Button(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 10.dp),
enabled = currentMgrId.value !== "" || mgrId.value !== "",
onClick = {
if (mgrId.value === "" && currentMgrId.value !== "") nextPage()
else confirm(mgrId.value, context, scope, settings, nextPage)
}
) {
Text("Continue")
}
}
}
}
@Suppress("RegExpRedundantEscape")
fun confirm(userId: String, context: Context, scope: CoroutineScope, settings: RemotrixSettings, done: () -> Unit){
val idPattern = Regex("@.+:[A-z0-9\\.-]+")
if(idPattern.matchEntire(userId) === null){
Toast.makeText(context, "The ID you have entered is invalid.", Toast.LENGTH_SHORT).show()
return
}
scope.launch {
settings.saveManagerId(userId)
Toast.makeText(context, "Manager set.", Toast.LENGTH_SHORT).show()
done()
}
}
@@ -0,0 +1,72 @@
package ch.skew.remotrix.setup
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ListItem
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.unit.dp
import ch.skew.remotrix.R
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun Welcome(
nextPage: () -> Unit
){
Scaffold(
topBar = {
TopAppBar({
Text(stringResource(R.string.welcome))
})
}
) { padding ->
val scroll = rememberScrollState()
Column(
modifier = Modifier
.padding(padding)
.fillMaxWidth()
.verticalScroll(scroll),
verticalArrangement = Arrangement.spacedBy(10.dp)
) {
ListItem(
headlineContent = { Text("What does this app do?") },
supportingContent = {
Text("This app will forward messages that arrive on this phone to various rooms over Matrix. Note that this app uses the space feature of Matrix to organise the rooms. Do look it up if you are not familiar with it.")
Text(
buildAnnotatedString {
append("Once your phone receives a message, the ")
withStyle(style = SpanStyle(fontWeight = FontWeight.Bold)) {
append("bot account")
}
append(" will create a room under the messaging space, then invites the ")
withStyle(style = SpanStyle(fontWeight = FontWeight.Bold)) {
append("manager account")
}
append(" into it.")
}
)
}
)
Button(
modifier = Modifier.fillMaxWidth().padding(horizontal = 10.dp),
onClick = nextPage
) {
Text("Continue")
}
}
}
}
@@ -0,0 +1,11 @@
package ch.skew.remotrix.ui.theme
import androidx.compose.ui.graphics.Color
val Purple80 = Color(0xFFD0BCFF)
val PurpleGrey80 = Color(0xFFCCC2DC)
val Pink80 = Color(0xFFEFB8C8)
val Purple40 = Color(0xFF6650a4)
val PurpleGrey40 = Color(0xFF625b71)
val Pink40 = Color(0xFF7D5260)
@@ -0,0 +1,70 @@
package ch.skew.remotrix.ui.theme
import android.app.Activity
import android.os.Build
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView
import androidx.core.view.WindowCompat
private val DarkColorScheme = darkColorScheme(
primary = Purple80,
secondary = PurpleGrey80,
tertiary = Pink80
)
private val LightColorScheme = lightColorScheme(
primary = Purple40,
secondary = PurpleGrey40,
tertiary = Pink40
/* Other default colors to override
background = Color(0xFFFFFBFE),
surface = Color(0xFFFFFBFE),
onPrimary = Color.White,
onSecondary = Color.White,
onTertiary = Color.White,
onBackground = Color(0xFF1C1B1F),
onSurface = Color(0xFF1C1B1F),
*/
)
@Composable
fun RemotrixTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
// Dynamic color is available on Android 12+
dynamicColor: Boolean = true,
content: @Composable () -> Unit
) {
val colorScheme = when {
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
val context = LocalContext.current
if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context)
}
darkTheme -> DarkColorScheme
else -> LightColorScheme
}
val view = LocalView.current
if (!view.isInEditMode) {
SideEffect {
val window = (view.context as Activity).window
window.statusBarColor = colorScheme.primary.toArgb()
WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme
}
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
}
@@ -0,0 +1,34 @@
package ch.skew.remotrix.ui.theme
import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with
val Typography = Typography(
bodyLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.5.sp
)
/* Other default text styles to override
titleLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 22.sp,
lineHeight = 28.sp,
letterSpacing = 0.sp
),
labelSmall = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Medium,
fontSize = 11.sp,
lineHeight = 16.sp,
letterSpacing = 0.5.sp
)
*/
)
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="cannot_logout_data_not_found">Cannot locate account data. Account will be removed from device only.</string>
<string name="logout_successful">Logout successful.</string>
<string name="cannot_logout_no_account">Cannot logout. Account will be removed from device only.</string>
<string name="invitation_sent">Invitation has been sent to manager account.</string>
<string name="reinvite_manager">Re-invite manager</string>
</resources>
@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="unknown_command">Unknown command. Enter !help for more details.</string>
<string name="pong">Pong!</string>
<string name="kick_error">Error: Cannot get all users to kick.</string>
<string name="cannot_delete_management_room">You cannot delete management rooms. You can delete this by removing this account from Remotrix app.</string>
<string name="error_cannot_kick_user">Error: Cannot kick user %s.</string>
<string name="ready_to_accept_commands">%s is ready to accept commands. (You can disable this message in the settings)</string>
<string name="startup_1">This room has been created by %s on device %s. Any non-command messages sent into this room will be sent to %s.</string>
<string name="command_help_output">These are the currently available commands:\n !close: Close a room in a messaging space. Useful if you received an OTP SMS.\n !ping: Check if your phone service is running.\n !reload: Reloads Matrix clients on your phone.\n !say &amp;lt;Reply&amp;gt;: Sends a message as a reply in a SMS room. By default, you can exclude this to send SMS back.\n !new &amp;lt;Phone number&amp;gt;: Create a new chatroom on Matrix that sends messages to the given phone number. You will be invited into that room.</string>
<string name="failed_to_decrypt">Client failed to decrypt message. Client will reload; please try again.</string>
<string name="service_check_ok">Service check has been executed and is running well.</string>
<string name="error_reply_not_specified">Error: Reply message has not been specified.</string>
<string name="error_message_sending_failed">Error: Message sending failed! Please enable and check log.</string>
<string name="message_sent_successfully">Message sent successfully.</string>
<string name="error_sending_in_management_room">Error: You cannot send messages in management room.</string>
<string name="error_sms_receiver_not_specified">Error: SMS receiver has not been specified.</string>
<string name="error_cannot_create_messaging_room">Error: Messaging room cannot be created!</string>
<string name="error_invalid_phone_number">Error: Invalid phone number.</string>
<string name="room_already_exists">Room for that phone number already exists; Inviting you there now.</string>
<string name="error_encryption_not_enabled">Error: This chatroom does not have encryption enabled.</string>
</resources>
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="settings">Settings</string>
<string name="settings_desc">Modify forwarding settings.</string>
</resources>
@@ -0,0 +1,29 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="logs">Logs</string>
<string name="logging_disabled_alert">Logging feature is currently disabled. You can enable this in the settings.</string>
<string name="success">Success</string>
<string name="failure">Failure</string>
<string name="hide_successful_sends">Hide successful sends</string>
<string name="message_sending_failed">Message not yet sent, still in outbox.</string>
<string name="message_sent">Message sent successfully.</string>
<string name="message_dropped">Message not sent due to user rules.</string>
<string name="unrecognised_message_code">Message not sent due to unrecognised message type.</string>
<string name="no_suitable_forwarder">Message not sent because suitable forwarder could not be found.</string>
<string name="cannot_load_matrix_client">Message not sent because loading Matrix client failed.</string>
<string name="cannot_create_room">Message not sent because room for that sender could not be created.</string>
<string name="cannot_create_child_room">Message not sent because Matrix client cannot create child room.</string>
<string name="message_max_attempts_reached">Maximum message sending attempts reached; Message has been dropped.</string>
<string name="log_viewer_title">View Log Entry (ID: %s)</string>
<string name="message_status">Message Status</string>
<string name="sent_at">Sent At</string>
<string name="error_message">Error Message</string>
<string name="message_type">Message Type</string>
<string name="test_message">Test message</string>
<string name="sms_message">SMS message</string>
<string name="message_sent_as">Message Sent As</string>
<string name="unknown_sender">Unknown (likely removed from this app)</string>
<string name="message_content">Message Content</string>
<string name="unknown_forwarder">(Forwarder: Unknown (ID: %s))</string>
<string name="forwarder">(Forwarder: %s)</string>
</resources>
@@ -0,0 +1,21 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="logging_in">Logging in…</string>
<string name="joining_the_messaging_space">Joining the messaging space…</string>
<string name="checking_if_this_account_have_correct_permissions">Checking if this account have correct permissions…</string>
<string name="creating_management_room">Creating management room…</string>
<string name="appending_management_room_as_child_room">Appending management room as child room…</string>
<string name="inviting_manager_account">Inviting manager account…</string>
<string name="new_account">Add New Account</string>
<string name="homeserver_url_label">Homeserver URL (Defaults to Matrix.org)</string>
<string name="management_room_name">Management room for %s</string>
<string name="management_room_desc">User may send messages to this room in order to manage automated actions of account %s.</string>
<string name="cannot_create_management_room">Unable to create management room.</string>
<string name="no_child_space_permission">%s has no permission to create child room in the management space. Please grant it first.</string>
<string name="logged_in">Logged in as %s</string>
<string name="child_room_creation_failed">"Cannot create child room: "</string>
<string name="cannot_create_room_in_the_messaging_space">"Cannot create room in the messaging space: "</string>
<string name="auto">Automatically create messaging space</string>
<string name="manual">Enter existing messaging space ID</string>
<string name="sms_forwarder">SMS Forwarder</string>
</resources>
@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="choose_default_account">Choose Default Account</string>
<string name="choose_default_account_desc">Choose which account the message should be sent with if it matches no rules in the list.</string>
<string name="enable_logging">Enable Logging</string>
<string name="enable_logging_desc">Log all message sending attempts, both successful and unsuccessful. Message content will also be saved.</string>
<string name="delete_log">Delete Log</string>
<string name="delete_log_desc">Delete all logs stored.</string>
<string name="log_deleted">Log deleted.</string>
<string name="enable_service_ready_message">Enable service ready message</string>
<string name="enable_service_ready_message_desc">When your device is ready to receive commands (eg. when booting is complete), you will receive a message indicating this via management room.</string>
<string name="debug_settings">Debug Settings</string>
<string name="receive_message_on_service_check">Receive message on service check</string>
<string name="receive_message_on_service_check_desc">If set, forwarders will send a message whenever the app checks if the service is running.</string>
<string name="debug_menu">Debug Menu</string>
<string name="debug">Debug</string>
<string name="accounts">Accounts</string>
<string name="logging">Logging</string>
</resources>
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="welcome">Welcome</string>
</resources>
@@ -0,0 +1,60 @@
<resources>
<string name="app_name">Remotrix</string>
<string name="manage_accounts">Manage Accounts</string>
<string name="manage_accounts_desc">View, modify and delete accounts to send messages with</string>
<string name="account_list">Manage Accounts</string>
<string name="add_new_account">Add new account</string>
<string name="go_back">Go back</string>
<string name="username">Username</string>
<string name="password">Password</string>
<string name="hide_password">Hide password</string>
<string name="show_password">Show password</string>
<string name="log_in">Log In</string>
<string name="generic_error">Generic error.</string>
<string name="add_account_help">Press + in the top right corner to add a new account.</string>
<string name="setup">Setup</string>
<string name="delete">Delete</string>
<string name="cancel">Cancel</string>
<string name="del_account_help">Account will be logged out first, and cryptographic data on this device will be removed.</string>
<string name="del_account_title">Delete account %s?</string>
<string name="account_options">Account options</string>
<string name="send_test_message">Send test message</string>
<string name="test_msg">Test message sent from Remotrix at %s.</string>
<string name="test_msg_sent">Test message sent at %s; Check account management room for its arrival.</string>
<string name="set_manager_account">Reopen Setup Page</string>
<string name="set_manager_account_desc">Use this to update your admin account and bot space. Note that migration does not exist yet.</string>
<string name="confirm">Confirm</string>
<string name="manager_id">New Manager ID</string>
<string name="invalid_id">Invalid ID.</string>
<string name="setup_remotrix">Setup Remotrix</string>
<string name="welcome_1">Before we begin, some settings must be done. Note that while you can change them in the future, migration does not exist yet. As a result, it would be very tedious. Therefore, it is best to set these as if they cannot be changed later.</string>
<string name="welcome_2">First off, please enter an account name in the form of \'@username:example.com. The account entered will be used as admin account, and bots will respond to commands from this account.</string>
<string name="welcome_4">Management space is NOT mandatory, but recommended. For every bot account you add to this app, a management room, initially between the management user and the bot, will be created. If this is set, this room will be created under that space, which would make things rather tidy.</string>
<string name="set_admin_account">Set Admin Account</string>
<string name="example_account">\@username:example.com</string>
<string name="existing_space_id">Existing space ID</string>
<string name="sample_space_id">!unIntELLIgiBle:example.com</string>
<string name="invalid_space_id">Invalid space ID.</string>
<string name="setup_complete">Setup complete.</string>
<string name="management_space">Management Space</string>
<string name="message_space_id">Message Space ID</string>
<string name="msg_room_desc">Messages from %s</string>
<string name="choose">Choose</string>
<string name="current_status">Current Status</string>
<string name="settings_desc_warning">\nWarning: You have no rules nor default account set! Messages will not be sent with this setup.</string>
<string name="none_option">Drop messages that do not match any rules</string>
<string name="view_logs">View Logs</string>
<string name="view_logs_desc">View logs of the messages. Note that you must enable it in options prior.</string>
<string name="creating_messaging_space">Creating messaging space…</string>
<string name="remotrix_service">Remotrix service</string>
<string name="remotrix_service_desc">Remotrix service is running with %d accounts active.</string>
<string name="debug_menu_desc">For more verbose output for debugging</string>
<string name="no_default_forwarder_1">"You have not set any default forwarder or rules in the settings. "</string>
<string name="no_default_forwarder_2">If you do not set one, this app will not forward any messages!</string>
<string name="room_created">Room has been created.</string>
<string name="close">Close</string>
<string name="behaviour">Behaviour</string>
<string name="log_matrix_client_errors">Log Matrix client errors</string>
<string name="log_matrix_client_errors_desc">If set, any errors generated by the command service will be stored in the database.</string>
</resources>
@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="Theme.Remotrix" parent="android:Theme.Material.Light.NoActionBar" />
</resources>
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?><!--
Sample backup rules file; uncomment and customize as necessary.
See https://developer.android.com/guide/topics/data/autobackup
for details.
Note: This file is ignored for devices older than API 31
See https://developer.android.com/about/versions/12/backup-restore
-->
<full-backup-content>
<!--
<include domain="sharedpref" path="."/>
<exclude domain="sharedpref" path="device.xml"/>
-->
</full-backup-content>
@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="utf-8"?><!--
Sample data extraction rules file; uncomment and customize as necessary.
See https://developer.android.com/about/versions/12/backup-restore#xml-changes
for details.
-->
<data-extraction-rules>
<cloud-backup>
<!-- TODO: Use <include> and <exclude> to control what is backed up.
<include .../>
<exclude .../>
-->
</cloud-backup>
<!--
<device-transfer>
<include .../>
<exclude .../>
</device-transfer>
-->
</data-extraction-rules>
@@ -0,0 +1,17 @@
package ch.skew.remotrix
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
}
+1 -1
View File
@@ -1 +1 @@
include ':presentation', ':android-smsmms', ':domain', ':data', ':common'
include ':presentation', ':android-smsmms', ':domain', ':data', ':common', ':remotrix-sync'

Some files were not shown because too many files have changed in this diff Show More