wip: Android Gradle project, crash reports, docs, CI job, notices
This commit is contained in:
1 parent
47b7e02e81
commit
1b95e8b504
35 files changed
+1590
-9
No files matched your search
@@ -0,0 +1,74 @@
|
||||
package io.github.faumaray.tsc
|
||||
|
||||
import android.Manifest
|
||||
import android.content.Context
|
||||
import android.content.pm.PackageManager
|
||||
import android.os.Build
|
||||
|
||||
/**
|
||||
* What the Rust library (crates/tsc-android/src/bridge.rs) calls, from any
|
||||
* thread. Keep the names and signatures in step with it.
|
||||
*/
|
||||
object Bridge {
|
||||
private val app: TscApp get() = TscApp.instance
|
||||
|
||||
@JvmStatic
|
||||
fun context(): Context = app
|
||||
|
||||
/** Ask for the microphone (voice) and notification (services) permissions. */
|
||||
@JvmStatic
|
||||
fun requestPermissions() {
|
||||
val activity = MainActivity.current?.get() ?: return
|
||||
val wanted = buildList {
|
||||
add(Manifest.permission.RECORD_AUDIO)
|
||||
if (Build.VERSION.SDK_INT >= 33) add(Manifest.permission.POST_NOTIFICATIONS)
|
||||
}.filter { activity.checkSelfPermission(it) != PackageManager.PERMISSION_GRANTED }
|
||||
if (wanted.isNotEmpty()) {
|
||||
activity.runOnUiThread { activity.requestPermissions(wanted.toTypedArray(), 1) }
|
||||
}
|
||||
}
|
||||
|
||||
/** Run the voice service with this notification text; null stops it. */
|
||||
@JvmStatic
|
||||
fun setVoiceNotification(text: String?) {
|
||||
if (text == null) VoiceService.stop(app) else VoiceService.start(app, text)
|
||||
}
|
||||
|
||||
/** Ask the user to share the screen; the answer goes to Native.onScreenCaptureResult. */
|
||||
@JvmStatic
|
||||
fun requestScreenCapture(fps: Int, maxSize: Int) {
|
||||
val activity = MainActivity.current?.get()
|
||||
if (activity == null) {
|
||||
Native.onScreenCaptureResult(false, "the app is not in the foreground")
|
||||
return
|
||||
}
|
||||
activity.runOnUiThread { activity.requestScreenCapture(fps, maxSize) }
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
fun stopScreenCapture() {
|
||||
ScreenCaptureService.stop(app)
|
||||
}
|
||||
|
||||
/** Capture what the device plays; false without a running screen capture. */
|
||||
@JvmStatic
|
||||
fun startSystemAudio(): Boolean = ScreenCaptureService.startAudio()
|
||||
|
||||
@JvmStatic
|
||||
fun stopSystemAudio() {
|
||||
ScreenCaptureService.stopAudio()
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
fun secretGet(key: String): String? = SecretStore.get(app, key)
|
||||
|
||||
@JvmStatic
|
||||
fun secretSet(key: String, value: String) {
|
||||
SecretStore.set(app, key, value)
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
fun secretDelete(key: String) {
|
||||
SecretStore.delete(app, key)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package io.github.faumaray.tsc
|
||||
|
||||
import android.app.NativeActivity
|
||||
import android.content.Intent
|
||||
import android.media.projection.MediaProjectionManager
|
||||
import android.os.Bundle
|
||||
import java.lang.ref.WeakReference
|
||||
|
||||
/**
|
||||
* The window: a NativeActivity running `android_main` of libtsc_android.so
|
||||
* (the Slint UI). Kotlin only handles what needs an Activity: permission
|
||||
* prompts and the screen-capture consent dialog.
|
||||
*/
|
||||
class MainActivity : NativeActivity() {
|
||||
private var captureFps = 30
|
||||
private var captureMaxSize = 1920
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
current = WeakReference(this)
|
||||
super.onCreate(savedInstanceState)
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
if (current?.get() === this) current = null
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
/**
|
||||
* Back leaves the app like Home instead of finishing the activity, so the
|
||||
* window (and its state) stays while voice goes on in the background.
|
||||
*/
|
||||
@Deprecated("Deprecated in Java")
|
||||
override fun onBackPressed() {
|
||||
moveTaskToBack(true)
|
||||
}
|
||||
|
||||
/** Show the system's "start recording or casting?" dialog. */
|
||||
fun requestScreenCapture(fps: Int, maxSize: Int) {
|
||||
captureFps = fps
|
||||
captureMaxSize = maxSize
|
||||
val manager = getSystemService(MediaProjectionManager::class.java)
|
||||
@Suppress("DEPRECATION")
|
||||
startActivityForResult(manager.createScreenCaptureIntent(), REQUEST_SCREEN_CAPTURE)
|
||||
}
|
||||
|
||||
@Deprecated("Deprecated in Java")
|
||||
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
|
||||
@Suppress("DEPRECATION")
|
||||
super.onActivityResult(requestCode, resultCode, data)
|
||||
if (requestCode != REQUEST_SCREEN_CAPTURE) return
|
||||
if (resultCode == RESULT_OK && data != null) {
|
||||
// The service reports the outcome to Native.onScreenCaptureResult.
|
||||
ScreenCaptureService.start(this, resultCode, data, captureFps, captureMaxSize)
|
||||
} else {
|
||||
Native.onScreenCaptureResult(false, null)
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val REQUEST_SCREEN_CAPTURE = 1001
|
||||
|
||||
/** The activity in front, if any. */
|
||||
@Volatile
|
||||
var current: WeakReference<MainActivity>? = null
|
||||
private set
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package io.github.faumaray.tsc
|
||||
|
||||
import java.nio.ByteBuffer
|
||||
|
||||
/** Callbacks into the Rust library (crates/tsc-android/src/bridge.rs). */
|
||||
object Native {
|
||||
init {
|
||||
// Already loaded by the NativeActivity; this registers it for JNI
|
||||
// lookups from this class loader.
|
||||
System.loadLibrary("tsc_android")
|
||||
}
|
||||
|
||||
/** The user answered the screen-capture dialog (`error`: why it failed). */
|
||||
@JvmStatic
|
||||
external fun onScreenCaptureResult(granted: Boolean, error: String?)
|
||||
|
||||
/** An RGBA_8888 frame. Returns false when frames are no longer wanted. */
|
||||
@JvmStatic
|
||||
external fun onScreenFrame(
|
||||
pixels: ByteBuffer,
|
||||
width: Int,
|
||||
height: Int,
|
||||
rowStride: Int,
|
||||
timestampNs: Long,
|
||||
): Boolean
|
||||
|
||||
/** The projection ended (by the app, the user or the system). */
|
||||
@JvmStatic
|
||||
external fun onScreenCaptureStopped()
|
||||
|
||||
/**
|
||||
* `count` interleaved 48 kHz float samples of what the device plays.
|
||||
* Returns false when audio is no longer wanted.
|
||||
*/
|
||||
@JvmStatic
|
||||
external fun onSystemAudio(samples: FloatArray, count: Int, channels: Int, timestampNs: Long): Boolean
|
||||
|
||||
/** "Disconnect" in the voice notification. */
|
||||
@JvmStatic
|
||||
external fun onDisconnectVoice()
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package io.github.faumaray.tsc
|
||||
|
||||
import android.app.Notification
|
||||
import android.app.NotificationChannel
|
||||
import android.app.NotificationManager
|
||||
import android.app.PendingIntent
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
|
||||
/** Notification channels and the notifications of the foreground services. */
|
||||
object Notifications {
|
||||
const val CHANNEL_VOICE = "voice"
|
||||
const val CHANNEL_SCREEN = "screen"
|
||||
|
||||
fun createChannels(context: Context) {
|
||||
val manager = context.getSystemService(NotificationManager::class.java)
|
||||
manager.createNotificationChannel(
|
||||
NotificationChannel(
|
||||
CHANNEL_VOICE,
|
||||
context.getString(R.string.channel_voice),
|
||||
NotificationManager.IMPORTANCE_LOW,
|
||||
),
|
||||
)
|
||||
manager.createNotificationChannel(
|
||||
NotificationChannel(
|
||||
CHANNEL_SCREEN,
|
||||
context.getString(R.string.channel_screen),
|
||||
NotificationManager.IMPORTANCE_LOW,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
/** Tapping a notification brings the app back. */
|
||||
private fun openApp(context: Context): PendingIntent = PendingIntent.getActivity(
|
||||
context,
|
||||
0,
|
||||
Intent(context, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT),
|
||||
PendingIntent.FLAG_IMMUTABLE,
|
||||
)
|
||||
|
||||
fun ongoing(
|
||||
context: Context,
|
||||
channel: String,
|
||||
text: String,
|
||||
actionTitle: String,
|
||||
action: PendingIntent,
|
||||
): Notification = Notification.Builder(context, channel)
|
||||
.setSmallIcon(R.drawable.ic_notification)
|
||||
.setContentTitle(context.getString(R.string.app_name))
|
||||
.setContentText(text)
|
||||
.setContentIntent(openApp(context))
|
||||
.setOngoing(true)
|
||||
.setCategory(Notification.CATEGORY_CALL)
|
||||
.addAction(Notification.Action.Builder(null, actionTitle, action).build())
|
||||
.build()
|
||||
}
|
||||
@@ -0,0 +1,258 @@
|
||||
package io.github.faumaray.tsc
|
||||
|
||||
import android.Manifest
|
||||
import android.app.PendingIntent
|
||||
import android.app.Service
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.content.pm.ServiceInfo
|
||||
import android.graphics.PixelFormat
|
||||
import android.hardware.display.DisplayManager
|
||||
import android.hardware.display.VirtualDisplay
|
||||
import android.media.AudioAttributes
|
||||
import android.media.AudioFormat
|
||||
import android.media.AudioPlaybackCaptureConfiguration
|
||||
import android.media.AudioRecord
|
||||
import android.media.ImageReader
|
||||
import android.media.projection.MediaProjection
|
||||
import android.media.projection.MediaProjectionManager
|
||||
import android.os.Build
|
||||
import android.os.Handler
|
||||
import android.os.HandlerThread
|
||||
import android.os.IBinder
|
||||
import android.os.Looper
|
||||
import android.util.Log
|
||||
import android.view.Display
|
||||
import android.view.Surface
|
||||
import kotlin.concurrent.thread
|
||||
import kotlin.math.max
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
/**
|
||||
* Screen sharing: holds the MediaProjection (a `mediaProjection` foreground
|
||||
* service, as Android requires), mirrors the display into an ImageReader and
|
||||
* hands each RGBA frame to Native.onScreenFrame; optionally captures what the
|
||||
* device plays (AudioPlaybackCapture) for Native.onSystemAudio.
|
||||
*/
|
||||
class ScreenCaptureService : Service() {
|
||||
private var projection: MediaProjection? = null
|
||||
private var display: VirtualDisplay? = null
|
||||
private var reader: ImageReader? = null
|
||||
private var worker: HandlerThread? = null
|
||||
|
||||
@Volatile
|
||||
private var audioRunning = false
|
||||
private var audioThread: Thread? = null
|
||||
|
||||
private val main = Handler(Looper.getMainLooper())
|
||||
|
||||
override fun onBind(intent: Intent?): IBinder? = null
|
||||
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
if (intent == null || intent.action == ACTION_STOP) {
|
||||
stopSelf()
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
if (projection != null) return START_NOT_STICKY
|
||||
val stop = PendingIntent.getService(
|
||||
this,
|
||||
0,
|
||||
Intent(this, ScreenCaptureService::class.java).setAction(ACTION_STOP),
|
||||
PendingIntent.FLAG_IMMUTABLE,
|
||||
)
|
||||
val notification = Notifications.ongoing(
|
||||
this,
|
||||
Notifications.CHANNEL_SCREEN,
|
||||
getString(R.string.screen_sharing),
|
||||
getString(R.string.stop_sharing),
|
||||
stop,
|
||||
)
|
||||
try {
|
||||
// Must be in the foreground before getMediaProjection (Android 14).
|
||||
startForeground(ID, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION)
|
||||
val data = if (Build.VERSION.SDK_INT >= 33) {
|
||||
intent.getParcelableExtra(EXTRA_DATA, Intent::class.java)
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
intent.getParcelableExtra(EXTRA_DATA)
|
||||
} ?: throw IllegalStateException("no projection data")
|
||||
val manager = getSystemService(MediaProjectionManager::class.java)
|
||||
val projection = manager.getMediaProjection(intent.getIntExtra(EXTRA_RESULT, 0), data)
|
||||
?: throw IllegalStateException("the projection was refused")
|
||||
this.projection = projection
|
||||
instance = this
|
||||
startVideo(projection, intent.getIntExtra(EXTRA_FPS, 30), intent.getIntExtra(EXTRA_MAX_SIZE, 1920))
|
||||
Native.onScreenCaptureResult(true, null)
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "screen capture failed", e)
|
||||
Native.onScreenCaptureResult(false, e.message ?: e.toString())
|
||||
stopSelf()
|
||||
}
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
|
||||
private fun startVideo(projection: MediaProjection, fps: Int, maxSize: Int) {
|
||||
val worker = HandlerThread("tsc-screen").also { it.start() }
|
||||
this.worker = worker
|
||||
val handler = Handler(worker.looper)
|
||||
// The user or the system can end the projection (status bar chip,
|
||||
// screen lock); registered before the virtual display (Android 14).
|
||||
projection.registerCallback(object : MediaProjection.Callback() {
|
||||
override fun onStop() {
|
||||
main.post { stopSelf() }
|
||||
}
|
||||
}, handler)
|
||||
|
||||
val metrics = resources.displayMetrics
|
||||
val screen = getSystemService(DisplayManager::class.java).getDisplay(Display.DEFAULT_DISPLAY)
|
||||
val mode = screen.mode
|
||||
// The mode is in the display's natural orientation; match the current
|
||||
// one. (Rotating while sharing letterboxes the picture.)
|
||||
val rotated = screen.rotation == Surface.ROTATION_90 || screen.rotation == Surface.ROTATION_270
|
||||
val (fullWidth, fullHeight) = if (rotated) {
|
||||
mode.physicalHeight to mode.physicalWidth
|
||||
} else {
|
||||
mode.physicalWidth to mode.physicalHeight
|
||||
}
|
||||
val scale = minOf(1.0, maxSize.toDouble() / max(fullWidth, fullHeight))
|
||||
// Even sizes, as video encoders want.
|
||||
val width = ((fullWidth * scale).roundToInt() / 2 * 2).coerceAtLeast(2)
|
||||
val height = ((fullHeight * scale).roundToInt() / 2 * 2).coerceAtLeast(2)
|
||||
|
||||
val reader = ImageReader.newInstance(width, height, PixelFormat.RGBA_8888, 3)
|
||||
this.reader = reader
|
||||
val interval = 1_000_000_000L / fps.coerceIn(1, 60)
|
||||
var last = 0L
|
||||
reader.setOnImageAvailableListener({ r ->
|
||||
val image = r.acquireLatestImage() ?: return@setOnImageAvailableListener
|
||||
try {
|
||||
// The display renders at its own rate; pass on at most `fps`.
|
||||
if (image.timestamp - last < interval) return@setOnImageAvailableListener
|
||||
last = image.timestamp
|
||||
val plane = image.planes[0]
|
||||
val wanted = Native.onScreenFrame(plane.buffer, image.width, image.height, plane.rowStride, image.timestamp)
|
||||
if (!wanted) main.post { stopSelf() }
|
||||
} finally {
|
||||
image.close()
|
||||
}
|
||||
}, handler)
|
||||
display = projection.createVirtualDisplay(
|
||||
"tsc-screen",
|
||||
width,
|
||||
height,
|
||||
metrics.densityDpi,
|
||||
DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
|
||||
reader.surface,
|
||||
null,
|
||||
handler,
|
||||
)
|
||||
}
|
||||
|
||||
/** Capture media, game and unknown-usage playback as 48 kHz stereo float. */
|
||||
private fun startAudioCapture(): Boolean {
|
||||
val projection = projection ?: return false
|
||||
if (audioRunning) return true
|
||||
if (checkSelfPermission(Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
|
||||
return false
|
||||
}
|
||||
val config = AudioPlaybackCaptureConfiguration.Builder(projection)
|
||||
.addMatchingUsage(AudioAttributes.USAGE_MEDIA)
|
||||
.addMatchingUsage(AudioAttributes.USAGE_GAME)
|
||||
.addMatchingUsage(AudioAttributes.USAGE_UNKNOWN)
|
||||
.build()
|
||||
val format = AudioFormat.Builder()
|
||||
.setEncoding(AudioFormat.ENCODING_PCM_FLOAT)
|
||||
.setSampleRate(SAMPLE_RATE)
|
||||
.setChannelMask(AudioFormat.CHANNEL_IN_STEREO)
|
||||
.build()
|
||||
val minimum = AudioRecord.getMinBufferSize(SAMPLE_RATE, AudioFormat.CHANNEL_IN_STEREO, AudioFormat.ENCODING_PCM_FLOAT)
|
||||
val record = try {
|
||||
AudioRecord.Builder()
|
||||
.setAudioFormat(format)
|
||||
.setAudioPlaybackCaptureConfig(config)
|
||||
// A tenth of a second.
|
||||
.setBufferSizeInBytes(max(minimum, SAMPLE_RATE / 10 * 2 * 4))
|
||||
.build()
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "system audio capture unavailable", e)
|
||||
return false
|
||||
}
|
||||
audioRunning = true
|
||||
record.startRecording()
|
||||
audioThread = thread(name = "tsc-system-audio") {
|
||||
// 10 ms of stereo.
|
||||
val buffer = FloatArray(SAMPLE_RATE / 100 * 2)
|
||||
try {
|
||||
while (audioRunning) {
|
||||
val read = record.read(buffer, 0, buffer.size, AudioRecord.READ_BLOCKING)
|
||||
if (read < 0) break
|
||||
if (read > 0 && !Native.onSystemAudio(buffer, read, 2, System.nanoTime())) break
|
||||
}
|
||||
} finally {
|
||||
audioRunning = false
|
||||
record.stop()
|
||||
record.release()
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
private fun stopAudioCapture() {
|
||||
audioRunning = false
|
||||
audioThread?.join(500)
|
||||
audioThread = null
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
if (instance === this) instance = null
|
||||
stopAudioCapture()
|
||||
display?.release()
|
||||
display = null
|
||||
reader?.close()
|
||||
reader = null
|
||||
projection?.stop()
|
||||
projection = null
|
||||
worker?.quitSafely()
|
||||
worker = null
|
||||
Native.onScreenCaptureStopped()
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "ScreenCaptureService"
|
||||
private const val ID = 2
|
||||
private const val SAMPLE_RATE = 48_000
|
||||
private const val ACTION_STOP = "io.github.faumaray.tsc.STOP_SHARING"
|
||||
private const val EXTRA_RESULT = "result"
|
||||
private const val EXTRA_DATA = "data"
|
||||
private const val EXTRA_FPS = "fps"
|
||||
private const val EXTRA_MAX_SIZE = "max_size"
|
||||
|
||||
@Volatile
|
||||
private var instance: ScreenCaptureService? = null
|
||||
|
||||
/** Start capturing with the consent the user just gave. */
|
||||
fun start(context: Context, resultCode: Int, data: Intent, fps: Int, maxSize: Int) {
|
||||
val intent = Intent(context, ScreenCaptureService::class.java)
|
||||
.putExtra(EXTRA_RESULT, resultCode)
|
||||
.putExtra(EXTRA_DATA, data)
|
||||
.putExtra(EXTRA_FPS, fps)
|
||||
.putExtra(EXTRA_MAX_SIZE, maxSize)
|
||||
context.startForegroundService(intent)
|
||||
}
|
||||
|
||||
fun stop(context: Context) {
|
||||
context.stopService(Intent(context, ScreenCaptureService::class.java))
|
||||
}
|
||||
|
||||
fun startAudio(): Boolean {
|
||||
val service = instance ?: return false
|
||||
return service.startAudioCapture()
|
||||
}
|
||||
|
||||
fun stopAudio() {
|
||||
instance?.stopAudioCapture()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package io.github.faumaray.tsc
|
||||
|
||||
import android.content.Context
|
||||
import android.security.keystore.KeyGenParameterSpec
|
||||
import android.security.keystore.KeyProperties
|
||||
import android.util.Base64
|
||||
import android.util.Log
|
||||
import java.security.KeyStore
|
||||
import javax.crypto.Cipher
|
||||
import javax.crypto.KeyGenerator
|
||||
import javax.crypto.SecretKey
|
||||
import javax.crypto.spec.GCMParameterSpec
|
||||
|
||||
/**
|
||||
* Saved passwords (server, query), for the Rust side's `Secrets`.
|
||||
*
|
||||
* Each value is encrypted with AES-256-GCM under a key that never leaves the
|
||||
* Android Keystore (hardware-backed where available); the key name is the
|
||||
* associated data, so a value cannot be moved to another key. Only the
|
||||
* ciphertext is stored, in private preferences excluded from backups.
|
||||
*/
|
||||
object SecretStore {
|
||||
private const val TAG = "SecretStore"
|
||||
private const val KEYSTORE = "AndroidKeyStore"
|
||||
private const val KEY_ALIAS = "tsc-secrets"
|
||||
private const val PREFS = "secrets"
|
||||
private const val TRANSFORMATION = "AES/GCM/NoPadding"
|
||||
private const val IV_BYTES = 12
|
||||
private const val TAG_BITS = 128
|
||||
|
||||
private fun key(): SecretKey {
|
||||
val keyStore = KeyStore.getInstance(KEYSTORE).apply { load(null) }
|
||||
(keyStore.getKey(KEY_ALIAS, null) as? SecretKey)?.let { return it }
|
||||
val generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, KEYSTORE)
|
||||
generator.init(
|
||||
KeyGenParameterSpec.Builder(
|
||||
KEY_ALIAS,
|
||||
KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT,
|
||||
)
|
||||
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
|
||||
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
|
||||
.setKeySize(256)
|
||||
.build(),
|
||||
)
|
||||
return generator.generateKey()
|
||||
}
|
||||
|
||||
private fun prefs(context: Context) = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
|
||||
|
||||
/** The value, or null if none is saved or it cannot be decrypted. */
|
||||
@Synchronized
|
||||
fun get(context: Context, name: String): String? {
|
||||
val stored = prefs(context).getString(name, null) ?: return null
|
||||
return try {
|
||||
val bytes = Base64.decode(stored, Base64.NO_WRAP)
|
||||
val cipher = Cipher.getInstance(TRANSFORMATION)
|
||||
cipher.init(Cipher.DECRYPT_MODE, key(), GCMParameterSpec(TAG_BITS, bytes, 0, IV_BYTES))
|
||||
cipher.updateAAD(name.toByteArray())
|
||||
String(cipher.doFinal(bytes, IV_BYTES, bytes.size - IV_BYTES), Charsets.UTF_8)
|
||||
} catch (e: Exception) {
|
||||
// E.g. the key was lost (the device's lock screen was reset).
|
||||
Log.w(TAG, "cannot decrypt $name", e)
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun set(context: Context, name: String, value: String) {
|
||||
val cipher = Cipher.getInstance(TRANSFORMATION)
|
||||
cipher.init(Cipher.ENCRYPT_MODE, key())
|
||||
cipher.updateAAD(name.toByteArray())
|
||||
val sealed = cipher.iv + cipher.doFinal(value.toByteArray(Charsets.UTF_8))
|
||||
check(cipher.iv.size == IV_BYTES)
|
||||
prefs(context).edit().putString(name, Base64.encodeToString(sealed, Base64.NO_WRAP)).commit()
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun delete(context: Context, name: String) {
|
||||
prefs(context).edit().remove(name).commit()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package io.github.faumaray.tsc
|
||||
|
||||
import android.app.Application
|
||||
|
||||
/** The process's application object; the Rust side reaches Android through it. */
|
||||
class TscApp : Application() {
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
instance = this
|
||||
Notifications.createChannels(this)
|
||||
}
|
||||
|
||||
companion object {
|
||||
lateinit var instance: TscApp
|
||||
private set
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package io.github.faumaray.tsc
|
||||
|
||||
import android.app.Notification
|
||||
import android.app.NotificationManager
|
||||
import android.app.PendingIntent
|
||||
import android.app.Service
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.ServiceInfo
|
||||
import android.os.Build
|
||||
import android.os.IBinder
|
||||
import android.util.Log
|
||||
|
||||
/**
|
||||
* Foreground service while a voice connection exists: Android keeps the
|
||||
* process, the network and (type microphone) the microphone of an app in
|
||||
* the background only this way. The Rust side starts, updates and stops it.
|
||||
*/
|
||||
class VoiceService : Service() {
|
||||
override fun onBind(intent: Intent?): IBinder? = null
|
||||
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
if (intent?.action == ACTION_DISCONNECT) {
|
||||
Native.onDisconnectVoice()
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
val text = intent?.getStringExtra(EXTRA_TEXT) ?: getString(R.string.voice_connected)
|
||||
try {
|
||||
if (Build.VERSION.SDK_INT >= 30) {
|
||||
startForeground(ID, notification(this, text), ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE)
|
||||
} else {
|
||||
startForeground(ID, notification(this, text))
|
||||
}
|
||||
running = this
|
||||
} catch (e: RuntimeException) {
|
||||
// E.g. no microphone permission (Android 14 refuses the type):
|
||||
// voice then works only while the app is in front.
|
||||
Log.w(TAG, "voice service cannot run in the foreground", e)
|
||||
stopSelf()
|
||||
}
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
if (running === this) running = null
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val TAG = "VoiceService"
|
||||
private const val ID = 1
|
||||
private const val EXTRA_TEXT = "text"
|
||||
private const val ACTION_DISCONNECT = "io.github.faumaray.tsc.DISCONNECT"
|
||||
|
||||
@Volatile
|
||||
private var running: VoiceService? = null
|
||||
|
||||
private fun notification(context: Context, text: String): Notification {
|
||||
val disconnect = PendingIntent.getService(
|
||||
context,
|
||||
0,
|
||||
Intent(context, VoiceService::class.java).setAction(ACTION_DISCONNECT),
|
||||
PendingIntent.FLAG_IMMUTABLE,
|
||||
)
|
||||
return Notifications.ongoing(
|
||||
context,
|
||||
Notifications.CHANNEL_VOICE,
|
||||
text,
|
||||
context.getString(R.string.disconnect),
|
||||
disconnect,
|
||||
)
|
||||
}
|
||||
|
||||
/** Start the service, or update its notification when it runs. */
|
||||
fun start(context: Context, text: String) {
|
||||
val service = running
|
||||
if (service != null) {
|
||||
service.getSystemService(NotificationManager::class.java)
|
||||
.notify(ID, notification(service, text))
|
||||
return
|
||||
}
|
||||
try {
|
||||
context.startForegroundService(
|
||||
Intent(context, VoiceService::class.java).putExtra(EXTRA_TEXT, text),
|
||||
)
|
||||
} catch (e: RuntimeException) {
|
||||
// Not allowed from the background (Android 12+). Voice is
|
||||
// connected from the UI, so this should not happen.
|
||||
Log.w(TAG, "cannot start the voice service", e)
|
||||
}
|
||||
}
|
||||
|
||||
fun stop(context: Context) {
|
||||
context.stopService(Intent(context, VoiceService::class.java))
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user