Phone actions, groundwork: the executor and its settings, before the server's phone_action
CI / check (push) Canceled after 0s
CI / check (push) Canceled after 0s
- actions/PhoneActions: standard intents for alarm, timer, calendar insert, SMS and email drafts, dial (the dialler, never a call), open URL (http/https only), open app (package or launcher label), settings panels, automation broadcasts (never android.* / com.android.*); torch via CameraManager; media keys via AudioManager. - actions/Navigation: Google Maps (google.navigation:, the dir URL with waypoints, geo:0,0?q=; no adding to a running route, no stop) and OsmAnd through its intent API only (osmand.api:// navigate, navigate_gpx with route points as GPX data, navigate_search, stop_navigation; no OsmAnd code, which is GPLv3). add_stop re-plans here -> stop -> destination. - Optional OsmAnd get_info (Settings switch, after allowing LLeMbas inside OsmAnd): position and the running route's destination, through a see-through ResultActivity. - Settings › Navigation app: whichever is installed (both: ask), Google Maps, OsmAnd, ask. - Not wired yet: the confirm card and the capability wait for the server's spec 3.6.0 fixtures. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
19 files changed
+900
No files matched your search
@@ -0,0 +1,135 @@
|
||||
package eu.llembas.android.actions
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.ActivityNotFoundException
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.os.Bundle
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import kotlinx.coroutines.CompletableDeferred
|
||||
import kotlinx.coroutines.withTimeoutOrNull
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
import java.util.concurrent.atomic.AtomicInteger
|
||||
|
||||
/**
|
||||
* Carries out a phone action the person confirmed: [run] picks the way -- one intent, the torch, a
|
||||
* media key, or a navigation app -- and answers with done, failed (and why), never silence.
|
||||
*/
|
||||
object ActionRunner {
|
||||
// The reasons go back to the model as the tool's result, so they are written for it, in English.
|
||||
private const val NOT_POSSIBLE = "the phone cannot do this action with these arguments"
|
||||
private const val NO_NAV_APP = "no navigation app chosen or installed (Google Maps or OsmAnd)"
|
||||
private const val NO_DESTINATION =
|
||||
"a stop can only be added with the route's destination: name it (destination), or the person lets LLeMbas ask OsmAnd for it"
|
||||
private const val GOOGLE_CANNOT_STOP = "Google Maps cannot be told to stop navigating; the person stops it there"
|
||||
private const val OSMAND_NEEDS_COORDINATES = "OsmAnd takes a route through stops only with every point's lat and lon"
|
||||
|
||||
/**
|
||||
* [askOsmAnd]: Settings › Phone actions says the person allowed LLeMbas inside OsmAnd, so its
|
||||
* position and the running route's destination may be asked for (`get_info`).
|
||||
*/
|
||||
suspend fun run(context: Context, action: String, args: Args, nav: NavApp?, askOsmAnd: Boolean = false): ActionOutcome {
|
||||
when (action) {
|
||||
"torch" -> return PhoneActions.torch(context, args.bool("on"))
|
||||
"media" -> return PhoneActions.media(context, args.str("key").ifBlank { "play_pause" })
|
||||
"navigate", "add_stop", "search_nearby", "stop_navigation" -> return navigate(context, action, args, nav, askOsmAnd)
|
||||
}
|
||||
val intent = PhoneActions.intentFor(context, action, args)
|
||||
?: return ActionOutcome(ActionStatus.Failed, NOT_POSSIBLE)
|
||||
return PhoneActions.launch(context, intent, broadcast = action == "automation")
|
||||
}
|
||||
|
||||
private suspend fun navigate(context: Context, action: String, args: Args, nav: NavApp?, askOsmAnd: Boolean): ActionOutcome {
|
||||
val app = nav ?: return ActionOutcome(ActionStatus.Failed, NO_NAV_APP)
|
||||
val pkg = app.installed(context) ?: return ActionOutcome(ActionStatus.Failed, NO_NAV_APP)
|
||||
val travel = Travel.of(args.str("mode").ifBlank { null })
|
||||
// OsmAnd's own position and destination, if the person allowed LLeMbas to ask it.
|
||||
val info = if (app == NavApp.OsmAnd && askOsmAnd && action != "stop_navigation") osmandInfo(context, pkg) else null
|
||||
val step = when (action) {
|
||||
"navigate" -> args.place("destination")?.let { NavIntents.navigate(app, pkg, it, args.places("stops"), travel, info) }
|
||||
|
||||
"add_stop" -> args.place("stop")?.let {
|
||||
NavIntents.addStop(app, pkg, it, args.place("destination"), travel, info, NO_DESTINATION)
|
||||
}
|
||||
|
||||
"search_nearby" -> args.str("query").takeIf { it.isNotBlank() }?.let { NavIntents.searchNearby(app, pkg, it, info) }
|
||||
|
||||
else -> NavIntents.stop(app, pkg, GOOGLE_CANNOT_STOP)
|
||||
} ?: return ActionOutcome(ActionStatus.Failed, NOT_POSSIBLE)
|
||||
return when (step) {
|
||||
is NavStep.Unsupported -> ActionOutcome(ActionStatus.Failed, step.reason.ifBlank { OSMAND_NEEDS_COORDINATES })
|
||||
|
||||
// The map app comes to the front and stays: it answers nothing more until the person
|
||||
// leaves it, so its having taken the intent is "done".
|
||||
is NavStep.Launch -> PhoneActions.launch(context, step.intent)
|
||||
}
|
||||
}
|
||||
|
||||
/** OsmAnd's `get_info`, when the person allowed it inside OsmAnd; null otherwise, quietly. */
|
||||
private suspend fun osmandInfo(context: Context, pkg: String): OsmAndInfo? {
|
||||
val (code, extras) = forResult(context, NavIntents.osmandInfo(pkg), timeoutMs = 4_000) ?: return null
|
||||
return if (code == Activity.RESULT_OK) OsmAndInfo.of(extras) else null
|
||||
}
|
||||
|
||||
private val waiting = ConcurrentHashMap<Int, CompletableDeferred<Pair<Int, Bundle?>>>()
|
||||
private val ids = AtomicInteger()
|
||||
|
||||
/**
|
||||
* Start [intent] for its result through [ResultActivity] -- a see-through activity of the
|
||||
* app's own, so this works from the assistant's sheet (a voice-interaction session) as well.
|
||||
*/
|
||||
suspend fun forResult(context: Context, intent: Intent, timeoutMs: Long = 60_000): Pair<Int, Bundle?>? {
|
||||
val id = ids.incrementAndGet()
|
||||
val answer = CompletableDeferred<Pair<Int, Bundle?>>()
|
||||
waiting[id] = answer
|
||||
return try {
|
||||
context.startActivity(
|
||||
Intent(context, ResultActivity::class.java)
|
||||
.putExtra(ResultActivity.EXTRA_ID, id)
|
||||
.putExtra(ResultActivity.EXTRA_INTENT, intent)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
|
||||
)
|
||||
withTimeoutOrNull(timeoutMs) { answer.await() }
|
||||
} finally {
|
||||
waiting.remove(id)
|
||||
}
|
||||
}
|
||||
|
||||
internal fun answered(id: Int, code: Int, extras: Bundle?) {
|
||||
waiting[id]?.complete(code to extras)
|
||||
}
|
||||
|
||||
/** Asks another app for a result on [ActionRunner]'s behalf, then goes. Shows nothing of its own. */
|
||||
class ResultActivity : ComponentActivity() {
|
||||
private var id = 0
|
||||
private val launcher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
|
||||
answered(id, result.resultCode, result.data?.extras)
|
||||
finish()
|
||||
}
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
id = intent.getIntExtra(EXTRA_ID, 0)
|
||||
if (savedInstanceState != null) return
|
||||
@Suppress("DEPRECATION")
|
||||
val target = intent.getParcelableExtra<Intent>(EXTRA_INTENT)
|
||||
if (target == null) {
|
||||
answered(id, Activity.RESULT_CANCELED, null)
|
||||
finish()
|
||||
return
|
||||
}
|
||||
try {
|
||||
launcher.launch(target)
|
||||
} catch (e: ActivityNotFoundException) {
|
||||
answered(id, Activity.RESULT_FIRST_USER, null)
|
||||
finish()
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val EXTRA_ID = "eu.llembas.android.RESULT_ID"
|
||||
const val EXTRA_INTENT = "eu.llembas.android.RESULT_INTENT"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
package eu.llembas.android.actions
|
||||
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
|
||||
/** A place for a navigation app: coordinates when the model knows them, else words to search for. */
|
||||
data class Place(val name: String = "", val lat: Double? = null, val lon: Double? = null, val query: String = "") {
|
||||
val hasCoordinates: Boolean get() = lat != null && lon != null
|
||||
val label: String get() = name.ifBlank { query.ifBlank { if (hasCoordinates) "$lat, $lon" else "" } }
|
||||
|
||||
/** What a map app searches for: the words, else the name. */
|
||||
val searchText: String get() = query.ifBlank { name }
|
||||
}
|
||||
|
||||
/** The navigation apps the phone actions drive. */
|
||||
enum class NavApp(val id: String, val packages: List<String>) {
|
||||
GoogleMaps("google", listOf("com.google.android.apps.maps")),
|
||||
|
||||
// OsmAnd: `net.osmand.plus` is OsmAnd+ and the F-Droid build (OsmAnd~); `net.osmand` the free one.
|
||||
OsmAnd("osmand", listOf("net.osmand.plus", "net.osmand", "net.osmand.dev")),
|
||||
;
|
||||
|
||||
/** The package of this app on the phone, if it is installed. */
|
||||
fun installed(context: Context): String? = packages.firstOrNull { isInstalled(context, it) }
|
||||
|
||||
companion object {
|
||||
/**
|
||||
* Settings' choice among [installed]: the one named; by default whichever is installed, and
|
||||
* with both installed (or "ask"), null -- the card then offers each.
|
||||
*/
|
||||
fun chosen(pref: String, installed: List<NavApp>): NavApp? = when (pref) {
|
||||
PREF_ASK -> null
|
||||
"" -> installed.singleOrNull()
|
||||
else -> installed.firstOrNull { it.id == pref } ?: installed.singleOrNull()
|
||||
}
|
||||
|
||||
fun installedApps(context: Context): List<NavApp> = entries.filter { it.installed(context) != null }
|
||||
|
||||
const val PREF_ASK = "ask"
|
||||
|
||||
private fun isInstalled(context: Context, pkg: String): Boolean = runCatching {
|
||||
if (Build.VERSION.SDK_INT >= 33) {
|
||||
context.packageManager.getPackageInfo(pkg, PackageManager.PackageInfoFlags.of(0))
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
context.packageManager.getPackageInfo(pkg, 0)
|
||||
}
|
||||
}.isSuccess
|
||||
}
|
||||
}
|
||||
|
||||
/** How a person travels, as the action names it. */
|
||||
enum class Travel(val id: String, val google: String, val googleNav: String, val osmand: String) {
|
||||
Drive("drive", "driving", "d", "car"),
|
||||
Walk("walk", "walking", "w", "pedestrian"),
|
||||
Bike("bike", "bicycling", "b", "bicycle"),
|
||||
Transit("transit", "transit", "d", "public_transport"),
|
||||
;
|
||||
|
||||
companion object {
|
||||
fun of(id: String?): Travel = entries.firstOrNull { it.id == id } ?: Drive
|
||||
}
|
||||
}
|
||||
|
||||
/** One request to a navigation app: an [Intent], or why it cannot be done in that app. */
|
||||
sealed interface NavStep {
|
||||
data class Launch(val intent: Intent) : NavStep
|
||||
|
||||
data class Unsupported(val reason: String) : NavStep
|
||||
}
|
||||
|
||||
/**
|
||||
* What OsmAnd itself says about the route, when the person allowed LLeMbas to ask
|
||||
* (OsmAnd › Plugins › … › the app's "Location" access for its API): the phone's position and the
|
||||
* route's destination. Null when not allowed -- the actions then use what the model gave.
|
||||
*/
|
||||
data class OsmAndInfo(val lat: Double?, val lon: Double?, val destination: Place?) {
|
||||
companion object {
|
||||
fun of(extras: Bundle?): OsmAndInfo? {
|
||||
extras ?: return null
|
||||
fun d(key: String) = if (extras.containsKey(key)) extras.getDouble(key) else null
|
||||
val dLat = d("destination_lat")
|
||||
val dLon = d("destination_lon")
|
||||
return OsmAndInfo(d("lat"), d("lon"), if (dLat != null && dLon != null) Place(lat = dLat, lon = dLon) else null)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The intents, per app. Google Maps: a route to a place with up to a few stops (its `dir` URL),
|
||||
* a search near here (`geo:0,0?q=`); it cannot take a stop into a route already running, nor be
|
||||
* told to stop -- adding a stop there starts the route again through the stop. OsmAnd: its intent
|
||||
* API (`osmand.api://`, a URI protocol; no OsmAnd code in this app): navigate, a route through
|
||||
* stops as a GPX passed as data, a search near a position, stop navigation.
|
||||
*/
|
||||
object NavIntents {
|
||||
private const val GOOGLE_STOPS = 9
|
||||
|
||||
fun navigate(app: NavApp, pkg: String, destination: Place, stops: List<Place>, travel: Travel, info: OsmAndInfo?): NavStep = when (app) {
|
||||
NavApp.GoogleMaps -> google(pkg, destination, stops, travel)
|
||||
NavApp.OsmAnd -> osmand(pkg, destination, stops, travel, info)
|
||||
}
|
||||
|
||||
/** A stop on the way to the route's destination ([destination] from the model, else OsmAnd's own). */
|
||||
fun addStop(app: NavApp, pkg: String, stop: Place, destination: Place?, travel: Travel, info: OsmAndInfo?, noDestination: String): NavStep {
|
||||
val to = destination?.takeIf { it.hasCoordinates || it.searchText.isNotBlank() } ?: info?.destination ?: return NavStep.Unsupported(noDestination)
|
||||
return navigate(app, pkg, to, listOf(stop), travel, info)
|
||||
}
|
||||
|
||||
fun searchNearby(app: NavApp, pkg: String, query: String, info: OsmAndInfo?): NavStep = when {
|
||||
app == NavApp.OsmAnd && info?.lat != null && info.lon != null -> NavStep.Launch(
|
||||
osmandUri(
|
||||
pkg,
|
||||
"navigate_search",
|
||||
"dest_search_query" to query,
|
||||
"search_lat" to info.lat.toString(),
|
||||
"search_lon" to info.lon.toString(),
|
||||
"show_search_results" to "true",
|
||||
"force" to "true",
|
||||
),
|
||||
)
|
||||
|
||||
else -> NavStep.Launch(Intent(Intent.ACTION_VIEW, Uri.parse("geo:0,0?q=" + Uri.encode(query))).setPackage(pkg))
|
||||
}
|
||||
|
||||
fun stop(app: NavApp, pkg: String, unsupported: String): NavStep = when (app) {
|
||||
NavApp.OsmAnd -> NavStep.Launch(osmandUri(pkg, "stop_navigation"))
|
||||
NavApp.GoogleMaps -> NavStep.Unsupported(unsupported)
|
||||
}
|
||||
|
||||
/** OsmAnd's own account of the route (needs the person's grant inside OsmAnd). */
|
||||
fun osmandInfo(pkg: String): Intent = osmandUri(pkg, "get_info")
|
||||
|
||||
private fun google(pkg: String, destination: Place, stops: List<Place>, travel: Travel): NavStep {
|
||||
if (stops.isEmpty()) {
|
||||
val q = if (destination.hasCoordinates) "${destination.lat},${destination.lon}" else destination.searchText
|
||||
return NavStep.Launch(Intent(Intent.ACTION_VIEW, Uri.parse("google.navigation:q=${Uri.encode(q)}&mode=${travel.googleNav}")).setPackage(pkg))
|
||||
}
|
||||
val url = Uri.parse("https://www.google.com/maps/dir/").buildUpon()
|
||||
.appendQueryParameter("api", "1")
|
||||
.appendQueryParameter("destination", googlePlace(destination))
|
||||
.appendQueryParameter("waypoints", stops.take(GOOGLE_STOPS).joinToString("|") { googlePlace(it) })
|
||||
.appendQueryParameter("travelmode", travel.google)
|
||||
.appendQueryParameter("dir_action", "navigate")
|
||||
.build()
|
||||
return NavStep.Launch(Intent(Intent.ACTION_VIEW, url).setPackage(pkg))
|
||||
}
|
||||
|
||||
private fun googlePlace(p: Place) = if (p.hasCoordinates) "${p.lat},${p.lon}" else p.searchText
|
||||
|
||||
private fun osmand(pkg: String, destination: Place, stops: List<Place>, travel: Travel, info: OsmAndInfo?): NavStep {
|
||||
val route = stops + destination
|
||||
return when {
|
||||
// Through stops: OsmAnd follows a route given as GPX, which needs every point's coordinates.
|
||||
stops.isNotEmpty() && route.all { it.hasCoordinates } -> NavStep.Launch(
|
||||
osmandUri(pkg, "navigate_gpx", "force" to "true").putExtra("data", gpx(route)),
|
||||
)
|
||||
|
||||
stops.isNotEmpty() -> NavStep.Unsupported("")
|
||||
|
||||
destination.hasCoordinates -> NavStep.Launch(
|
||||
osmandUri(
|
||||
pkg,
|
||||
"navigate",
|
||||
"dest_lat" to destination.lat.toString(),
|
||||
"dest_lon" to destination.lon.toString(),
|
||||
"dest_name" to destination.label,
|
||||
"profile" to travel.osmand,
|
||||
"force" to "true",
|
||||
),
|
||||
)
|
||||
|
||||
// Words only: OsmAnd searches them near the phone when it says where the phone is,
|
||||
// else its own search opens with them (geo:0,0?q=).
|
||||
info?.lat != null && info.lon != null -> NavStep.Launch(
|
||||
osmandUri(
|
||||
pkg,
|
||||
"navigate_search",
|
||||
"dest_search_query" to destination.searchText,
|
||||
"search_lat" to info.lat.toString(),
|
||||
"search_lon" to info.lon.toString(),
|
||||
"profile" to travel.osmand,
|
||||
"force" to "true",
|
||||
),
|
||||
)
|
||||
|
||||
else -> NavStep.Launch(Intent(Intent.ACTION_VIEW, Uri.parse("geo:0,0?q=" + Uri.encode(destination.searchText))).setPackage(pkg))
|
||||
}
|
||||
}
|
||||
|
||||
private fun osmandUri(pkg: String, command: String, vararg params: Pair<String, String>): Intent {
|
||||
val uri = Uri.Builder().scheme("osmand.api").authority(command).apply { params.forEach { (k, v) -> appendQueryParameter(k, v) } }.build()
|
||||
return Intent(Intent.ACTION_VIEW, uri).setPackage(pkg)
|
||||
}
|
||||
|
||||
/** A route as GPX 1.1: its points in order, named. */
|
||||
fun gpx(points: List<Place>): String = buildString {
|
||||
append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
|
||||
append("<gpx version=\"1.1\" creator=\"LLeMbas\" xmlns=\"http://www.topografix.com/GPX/1/1\"><rte>")
|
||||
for (p in points) {
|
||||
append("<rtept lat=\"${p.lat}\" lon=\"${p.lon}\"><name>")
|
||||
append(p.label.replace("&", "&").replace("<", "<").replace(">", ">"))
|
||||
append("</name></rtept>")
|
||||
}
|
||||
append("</rte></gpx>\n")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
package eu.llembas.android.actions
|
||||
|
||||
import android.content.ActivityNotFoundException
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.hardware.camera2.CameraCharacteristics
|
||||
import android.hardware.camera2.CameraManager
|
||||
import android.media.AudioManager
|
||||
import android.net.Uri
|
||||
import android.provider.AlarmClock
|
||||
import android.provider.CalendarContract
|
||||
import android.provider.Settings
|
||||
import android.view.KeyEvent
|
||||
import kotlinx.serialization.json.JsonArray
|
||||
import kotlinx.serialization.json.JsonElement
|
||||
import kotlinx.serialization.json.JsonObject
|
||||
import kotlinx.serialization.json.JsonPrimitive
|
||||
import kotlinx.serialization.json.booleanOrNull
|
||||
import kotlinx.serialization.json.doubleOrNull
|
||||
import kotlinx.serialization.json.intOrNull
|
||||
import kotlinx.serialization.json.longOrNull
|
||||
import java.time.LocalDateTime
|
||||
import java.time.OffsetDateTime
|
||||
import java.time.ZoneId
|
||||
|
||||
/** How a phone action ended, as the tool's result says it. */
|
||||
enum class ActionStatus(val wire: String) { Done("done"), Declined("declined"), Failed("failed") }
|
||||
|
||||
data class ActionOutcome(val status: ActionStatus, val message: String = "")
|
||||
|
||||
/** The arguments of an action, read leniently: a model writes numbers as strings now and then. */
|
||||
class Args(val json: JsonObject) {
|
||||
private val o get() = json
|
||||
|
||||
fun str(key: String): String = (o[key] as? JsonPrimitive)?.takeIf { it.isString || it.booleanOrNull == null }?.content.orEmpty()
|
||||
|
||||
fun int(key: String): Int? = (o[key] as? JsonPrimitive)?.let { it.intOrNull ?: it.content.toIntOrNull() }
|
||||
|
||||
fun long(key: String): Long? = (o[key] as? JsonPrimitive)?.let { it.longOrNull ?: it.content.toLongOrNull() }
|
||||
|
||||
fun bool(key: String): Boolean? = (o[key] as? JsonPrimitive)?.let { it.booleanOrNull ?: it.content.toBooleanStrictOrNull() }
|
||||
|
||||
fun obj(key: String): Args? = (o[key] as? JsonObject)?.let(::Args)
|
||||
|
||||
fun list(key: String): List<JsonElement> = (o[key] as? JsonArray).orEmpty()
|
||||
|
||||
fun place(key: String): Place? = when (val v = o[key]) {
|
||||
is JsonObject -> placeOf(v)
|
||||
is JsonPrimitive -> v.content.takeIf { it.isNotBlank() }?.let { Place(query = it) }
|
||||
else -> null
|
||||
}
|
||||
|
||||
fun places(key: String): List<Place> = list(key).mapNotNull { e ->
|
||||
when (e) {
|
||||
is JsonObject -> placeOf(e)
|
||||
is JsonPrimitive -> e.content.takeIf { it.isNotBlank() }?.let { Place(query = it) }
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
|
||||
private fun placeOf(v: JsonObject): Place {
|
||||
fun d(k: String) = (v[k] as? JsonPrimitive)?.let { it.doubleOrNull ?: it.content.toDoubleOrNull() }
|
||||
return Place(
|
||||
name = (v["name"] as? JsonPrimitive)?.content.orEmpty(),
|
||||
lat = d("lat"),
|
||||
lon = d("lon"),
|
||||
query = (v["query"] as? JsonPrimitive)?.content.orEmpty(),
|
||||
)
|
||||
}
|
||||
|
||||
/** A time the model wrote: ISO 8601 with an offset, or local (the phone's zone). */
|
||||
fun time(key: String): Long? {
|
||||
val raw = str(key).ifBlank { return null }
|
||||
return runCatching { OffsetDateTime.parse(raw).toInstant().toEpochMilli() }.getOrNull()
|
||||
?: runCatching { LocalDateTime.parse(raw).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli() }.getOrNull()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The phone actions a model may propose (`phone_action`), carried out with Android's standard
|
||||
* intents once the person tapped Do it on the card. Each one either opens the app that does it,
|
||||
* with everything filled in (an alarm, an event, a draft -- the person sends a message or saves
|
||||
* an event there themselves), or does a small thing at once (the torch, play/pause).
|
||||
*
|
||||
* Nothing here runs without the card's Do it, and none of it from the lock screen. A model's
|
||||
* words are data: a URL opens only for http and https, a broadcast never names a system action,
|
||||
* a phone number goes to the dialler and is never called.
|
||||
*/
|
||||
object PhoneActions {
|
||||
/** Media keys the `media` action sends. */
|
||||
private val MEDIA = mapOf(
|
||||
"play_pause" to KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE,
|
||||
"play" to KeyEvent.KEYCODE_MEDIA_PLAY,
|
||||
"pause" to KeyEvent.KEYCODE_MEDIA_PAUSE,
|
||||
"next" to KeyEvent.KEYCODE_MEDIA_NEXT,
|
||||
"previous" to KeyEvent.KEYCODE_MEDIA_PREVIOUS,
|
||||
"stop" to KeyEvent.KEYCODE_MEDIA_STOP,
|
||||
)
|
||||
|
||||
/** Settings panels, by the action's name. Panels (Android 10+) float over the app; the rest are pages. */
|
||||
private val PANELS = mapOf(
|
||||
"wifi" to Settings.Panel.ACTION_WIFI,
|
||||
"internet" to Settings.Panel.ACTION_INTERNET_CONNECTIVITY,
|
||||
"nfc" to Settings.Panel.ACTION_NFC,
|
||||
"volume" to Settings.Panel.ACTION_VOLUME,
|
||||
"bluetooth" to Settings.ACTION_BLUETOOTH_SETTINGS,
|
||||
"location" to Settings.ACTION_LOCATION_SOURCE_SETTINGS,
|
||||
"display" to Settings.ACTION_DISPLAY_SETTINGS,
|
||||
"battery" to Intent.ACTION_POWER_USAGE_SUMMARY,
|
||||
"airplane" to Settings.ACTION_AIRPLANE_MODE_SETTINGS,
|
||||
"do_not_disturb" to Settings.ACTION_ZEN_MODE_PRIORITY_SETTINGS,
|
||||
)
|
||||
|
||||
/** A broadcast an automation app (Tasker, Automate, MacroDroid) listens for: never a system one. */
|
||||
fun broadcastAllowed(action: String): Boolean =
|
||||
action.isNotBlank() && action.length <= 200 && !action.startsWith("android.") && !action.startsWith("com.android.") &&
|
||||
Regex("^[A-Za-z0-9_.]+$").matches(action)
|
||||
|
||||
/** A URL the phone may open for a model: web pages only. */
|
||||
fun urlAllowed(url: String): Boolean = Uri.parse(url.trim()).scheme?.lowercase() in setOf("http", "https")
|
||||
|
||||
/**
|
||||
* The intent for an action that is one intent (everything but navigation, the torch and media
|
||||
* keys), or null when [action] is not one of these.
|
||||
*/
|
||||
fun intentFor(context: Context, action: String, a: Args): Intent? = when (action) {
|
||||
"alarm" -> Intent(AlarmClock.ACTION_SET_ALARM)
|
||||
.putExtra(AlarmClock.EXTRA_HOUR, a.int("hour") ?: 7)
|
||||
.putExtra(AlarmClock.EXTRA_MINUTES, a.int("minute") ?: 0)
|
||||
.apply { a.str("label").takeIf { it.isNotBlank() }?.let { putExtra(AlarmClock.EXTRA_MESSAGE, it) } }
|
||||
.apply {
|
||||
val days = a.list("days").mapNotNull { (it as? JsonPrimitive)?.content?.let(::calendarDay) }
|
||||
if (days.isNotEmpty()) putIntegerArrayListExtra(AlarmClock.EXTRA_DAYS, ArrayList(days))
|
||||
}
|
||||
|
||||
"timer" -> Intent(AlarmClock.ACTION_SET_TIMER)
|
||||
.putExtra(AlarmClock.EXTRA_LENGTH, (a.int("seconds") ?: 60).coerceIn(1, 86_400))
|
||||
.putExtra(AlarmClock.EXTRA_SKIP_UI, false)
|
||||
.apply { a.str("label").takeIf { it.isNotBlank() }?.let { putExtra(AlarmClock.EXTRA_MESSAGE, it) } }
|
||||
|
||||
"calendar_event" -> Intent(Intent.ACTION_INSERT, CalendarContract.Events.CONTENT_URI)
|
||||
.putExtra(CalendarContract.Events.TITLE, a.str("title"))
|
||||
.apply {
|
||||
a.time("start")?.let { putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, it) }
|
||||
a.time("end")?.let { putExtra(CalendarContract.EXTRA_EVENT_END_TIME, it) }
|
||||
if (a.bool("all_day") == true) putExtra(CalendarContract.EXTRA_EVENT_ALL_DAY, true)
|
||||
a.str("location").takeIf { it.isNotBlank() }?.let { putExtra(CalendarContract.Events.EVENT_LOCATION, it) }
|
||||
a.str("description").takeIf { it.isNotBlank() }?.let { putExtra(CalendarContract.Events.DESCRIPTION, it) }
|
||||
}
|
||||
|
||||
"sms_draft" -> Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:" + Uri.encode(a.str("to"))))
|
||||
.putExtra("sms_body", a.str("body"))
|
||||
|
||||
"email_draft" -> Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:"))
|
||||
.putExtra(
|
||||
Intent.EXTRA_EMAIL,
|
||||
a.list("to").mapNotNull {
|
||||
(it as? JsonPrimitive)?.content
|
||||
}.ifEmpty { listOf(a.str("to")) }.filter { it.isNotBlank() }.toTypedArray(),
|
||||
)
|
||||
.putExtra(Intent.EXTRA_SUBJECT, a.str("subject"))
|
||||
.putExtra(Intent.EXTRA_TEXT, a.str("body"))
|
||||
|
||||
// The dialler with the number in it: the person presses call.
|
||||
"dial" -> Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + Uri.encode(a.str("number"))))
|
||||
|
||||
"open_url" -> a.str("url").trim().takeIf(::urlAllowed)?.let { Intent(Intent.ACTION_VIEW, Uri.parse(it)) }
|
||||
|
||||
"open_app" -> appIntent(context, a.str("package"), a.str("name"))
|
||||
|
||||
"settings_panel" -> PANELS[a.str("panel")]?.let { Intent(it) }
|
||||
|
||||
"automation" -> a.str("action").takeIf(::broadcastAllowed)?.let { name ->
|
||||
Intent(name).apply {
|
||||
a.str("package").takeIf { it.isNotBlank() }?.let { setPackage(it) }
|
||||
a.obj("extras")?.let { extras ->
|
||||
// Strings only: an automation app reads its variables as text.
|
||||
extras.json.forEach { (k, v) -> (v as? JsonPrimitive)?.let { putExtra(k, it.content) } }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
else -> null
|
||||
}
|
||||
|
||||
/** An app by its package, else by the name the launcher shows (the first app whose label matches). */
|
||||
fun appIntent(context: Context, pkg: String, name: String): Intent? {
|
||||
val pm = context.packageManager
|
||||
pkg.takeIf { it.isNotBlank() }?.let { p -> pm.getLaunchIntentForPackage(p)?.let { return it } }
|
||||
if (name.isBlank()) return null
|
||||
val launcher = Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER)
|
||||
val apps = runCatching { pm.queryIntentActivities(launcher, PackageManager.MATCH_ALL) }.getOrDefault(emptyList())
|
||||
val wanted = name.trim().lowercase()
|
||||
val found = apps.firstOrNull { it.loadLabel(pm).toString().lowercase() == wanted }
|
||||
?: apps.firstOrNull { it.loadLabel(pm).toString().lowercase().contains(wanted) }
|
||||
?: return null
|
||||
return pm.getLaunchIntentForPackage(found.activityInfo.packageName)
|
||||
}
|
||||
|
||||
/** The torch on or off (or the other way round), through the camera service; no permission needed. */
|
||||
fun torch(context: Context, on: Boolean?): ActionOutcome {
|
||||
val cameras = context.getSystemService(CameraManager::class.java) ?: return ActionOutcome(ActionStatus.Failed, "no camera")
|
||||
val id = cameras.cameraIdList.firstOrNull { cameras.getCameraCharacteristics(it).get(CameraCharacteristics.FLASH_INFO_AVAILABLE) == true }
|
||||
?: return ActionOutcome(ActionStatus.Failed, "this phone has no torch")
|
||||
val target = on ?: !torchOn
|
||||
return runCatching {
|
||||
cameras.setTorchMode(id, target)
|
||||
torchOn = target
|
||||
ActionOutcome(ActionStatus.Done, if (target) "torch on" else "torch off")
|
||||
}.getOrElse { ActionOutcome(ActionStatus.Failed, it.message.orEmpty()) }
|
||||
}
|
||||
|
||||
@Volatile
|
||||
private var torchOn = false
|
||||
|
||||
/** A media key to whatever is playing. */
|
||||
fun media(context: Context, key: String): ActionOutcome {
|
||||
val code = MEDIA[key] ?: return ActionOutcome(ActionStatus.Failed, "unknown media key: $key")
|
||||
val audio = context.getSystemService(AudioManager::class.java) ?: return ActionOutcome(ActionStatus.Failed, "no audio")
|
||||
audio.dispatchMediaKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, code))
|
||||
audio.dispatchMediaKeyEvent(KeyEvent(KeyEvent.ACTION_UP, code))
|
||||
return ActionOutcome(ActionStatus.Done, key)
|
||||
}
|
||||
|
||||
/** Start [intent] as a new task; whether an app took it. */
|
||||
fun launch(context: Context, intent: Intent, broadcast: Boolean = false): ActionOutcome = try {
|
||||
if (broadcast) {
|
||||
context.sendBroadcast(intent)
|
||||
} else {
|
||||
context.startActivity(intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
|
||||
}
|
||||
ActionOutcome(ActionStatus.Done)
|
||||
} catch (e: ActivityNotFoundException) {
|
||||
ActionOutcome(ActionStatus.Failed, "no app on this phone does that")
|
||||
} catch (e: SecurityException) {
|
||||
ActionOutcome(ActionStatus.Failed, e.message.orEmpty())
|
||||
}
|
||||
|
||||
private fun calendarDay(day: String): Int? = when (day.lowercase().take(3)) {
|
||||
"sun" -> java.util.Calendar.SUNDAY
|
||||
"mon" -> java.util.Calendar.MONDAY
|
||||
"tue" -> java.util.Calendar.TUESDAY
|
||||
"wed" -> java.util.Calendar.WEDNESDAY
|
||||
"thu" -> java.util.Calendar.THURSDAY
|
||||
"fri" -> java.util.Calendar.FRIDAY
|
||||
"sat" -> java.util.Calendar.SATURDAY
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
@@ -95,6 +95,10 @@ data class Prefs(
|
||||
val wakeScreenOnly: Boolean = true,
|
||||
/** The assistant may read the notifications when asked (with Android's notification access). */
|
||||
val notificationSummaries: Boolean = false,
|
||||
/** Phone actions' navigation app: "" whichever is installed, "google", "osmand", or "ask". */
|
||||
val navApp: String = "",
|
||||
/** Ask OsmAnd for the phone's position and the route's destination (allowed inside OsmAnd first). */
|
||||
val osmandInfo: Boolean = false,
|
||||
val assistantModel: String = "",
|
||||
val lastAssistChat: String = "",
|
||||
val lastAssistTitle: String = "",
|
||||
|
||||
@@ -38,6 +38,8 @@ import androidx.compose.material.icons.filled.Forum
|
||||
import androidx.compose.material.icons.filled.Hearing
|
||||
import androidx.compose.material.icons.filled.Info
|
||||
import androidx.compose.material.icons.filled.Mic
|
||||
import androidx.compose.material.icons.filled.MyLocation
|
||||
import androidx.compose.material.icons.filled.Navigation
|
||||
import androidx.compose.material.icons.filled.Notifications
|
||||
import androidx.compose.material.icons.filled.NotificationsActive
|
||||
import androidx.compose.material.icons.filled.Palette
|
||||
@@ -84,6 +86,7 @@ import androidx.core.content.ContextCompat
|
||||
import eu.llembas.android.AppLanguage
|
||||
import eu.llembas.android.BuildConfig
|
||||
import eu.llembas.android.R
|
||||
import eu.llembas.android.actions.NavApp
|
||||
import eu.llembas.android.assist.PhoneRecognizer
|
||||
import eu.llembas.android.auth.Instance
|
||||
import eu.llembas.android.auth.Prefs
|
||||
@@ -123,6 +126,8 @@ interface SettingsActions {
|
||||
fun batterySettings() {}
|
||||
fun notificationSummaries(on: Boolean) {}
|
||||
fun notificationAccess() {}
|
||||
fun navApp(id: String) {}
|
||||
fun osmandInfo(on: Boolean) {}
|
||||
fun readAloud(on: Boolean) {}
|
||||
fun checkUpdate() {}
|
||||
fun openRelease() {}
|
||||
@@ -151,6 +156,8 @@ data class SettingsState(
|
||||
val wakeAvailable: Boolean = false,
|
||||
/** Whether Android's notification access is given to LLeMbas. */
|
||||
val notificationAccess: Boolean = false,
|
||||
/** The navigation apps installed: NavApp ids. */
|
||||
val navApps: List<String> = emptyList(),
|
||||
)
|
||||
|
||||
@Composable
|
||||
@@ -274,6 +281,14 @@ fun SettingsScreen(onBack: () -> Unit, onAddInstance: () -> Unit) {
|
||||
runCatching { context.startActivity(NotificationReader.settingsIntent(context)) }
|
||||
}
|
||||
|
||||
override fun navApp(id: String) {
|
||||
scope.launch { store.savePrefs { it.copy(navApp = id) } }
|
||||
}
|
||||
|
||||
override fun osmandInfo(on: Boolean) {
|
||||
scope.launch { store.savePrefs { it.copy(osmandInfo = on) } }
|
||||
}
|
||||
|
||||
override fun readAloud(on: Boolean) {
|
||||
scope.launch { store.savePrefs { it.copy(readAloudSpoken = on) } }
|
||||
}
|
||||
@@ -331,6 +346,7 @@ fun SettingsScreen(onBack: () -> Unit, onAddInstance: () -> Unit) {
|
||||
wakeAvailable = WakeEngine.AVAILABLE,
|
||||
// Read again each time Settings is composed: the person comes back from the system's page.
|
||||
notificationAccess = NotificationReader.granted(context),
|
||||
navApps = remember { NavApp.installedApps(context).map { it.id } },
|
||||
),
|
||||
actions,
|
||||
onBack,
|
||||
@@ -514,6 +530,7 @@ fun SettingsContent(state: SettingsState, actions: SettingsActions, onBack: () -
|
||||
}
|
||||
item { WakeWordGroup(state, actions) }
|
||||
item { NotificationSummaryGroup(state, actions) }
|
||||
item { PhoneActionsGroup(state, actions) }
|
||||
item {
|
||||
// Which recogniser turns speech into words: the instance's or the phone's -- what
|
||||
// each one is, and where the recording goes, said in the row itself.
|
||||
@@ -648,6 +665,53 @@ private fun WakeWordGroup(state: SettingsState, actions: SettingsActions) {
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Phone actions: which navigation app a route goes to (whichever is installed by default; with
|
||||
* both, the card asks), and whether OsmAnd may be asked where the phone is and where the running
|
||||
* route goes -- which the person allows inside OsmAnd first.
|
||||
*/
|
||||
@Composable
|
||||
private fun PhoneActionsGroup(state: SettingsState, actions: SettingsActions) {
|
||||
val palette = LocalPalette.current
|
||||
val choices = listOf(
|
||||
"" to stringResource(R.string.nav_app_auto),
|
||||
NavApp.GoogleMaps.id to stringResource(R.string.nav_app_google),
|
||||
NavApp.OsmAnd.id to stringResource(R.string.nav_app_osmand),
|
||||
NavApp.PREF_ASK to stringResource(R.string.nav_app_ask),
|
||||
)
|
||||
Group(stringResource(R.string.nav_app)) {
|
||||
choices.forEachIndexed { i, (id, label) ->
|
||||
if (i > 0) Rule()
|
||||
val installed = id == "" || id == NavApp.PREF_ASK || id in state.navApps
|
||||
SettingRow(
|
||||
Icons.Filled.Navigation,
|
||||
label,
|
||||
subtitle = if (installed) null else stringResource(R.string.nav_app_not_installed),
|
||||
showIcon = i == 0,
|
||||
enabled = installed,
|
||||
onClick = { actions.navApp(id) },
|
||||
trailing = { RadioButton(selected = state.prefs.navApp == id, enabled = installed, onClick = { actions.navApp(id) }) },
|
||||
)
|
||||
}
|
||||
if (NavApp.OsmAnd.id in state.navApps) {
|
||||
Rule()
|
||||
SettingRow(
|
||||
Icons.Filled.MyLocation,
|
||||
stringResource(R.string.osmand_info),
|
||||
subtitle = stringResource(R.string.osmand_info_line),
|
||||
onClick = { actions.osmandInfo(!state.prefs.osmandInfo) },
|
||||
trailing = { Switch(checked = state.prefs.osmandInfo, onCheckedChange = actions::osmandInfo) },
|
||||
)
|
||||
}
|
||||
}
|
||||
Text(
|
||||
stringResource(R.string.phone_actions_line),
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = palette.inkFaint,
|
||||
modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
|
||||
)
|
||||
}
|
||||
|
||||
/** Notification summaries: off by default; on needs Android's notification access too, which this explains. */
|
||||
@Composable
|
||||
private fun NotificationSummaryGroup(state: SettingsState, actions: SettingsActions) {
|
||||
|
||||
Reference in new issue
Block a user