forked from eatvio/eatvio_app
feat(video_calls): call accepting and declingn handling
This commit is contained in:
@@ -0,0 +1,10 @@
|
||||
package com.eatvioapp.app
|
||||
|
||||
import android.app.Application
|
||||
|
||||
class EatvioApplication : Application() {
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
VideoCallDeclineReporter.install(this)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package com.eatvioapp.app
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
|
||||
internal object FlutterSharedPrefs {
|
||||
const val NAME = "FlutterSharedPreferences"
|
||||
private const val PREFIX = "flutter."
|
||||
|
||||
fun string(context: Context, key: String): String? {
|
||||
return context
|
||||
.getSharedPreferences(NAME, Context.MODE_PRIVATE)
|
||||
.getString(PREFIX + key, null)
|
||||
?.trim()
|
||||
?.takeIf { it.isNotEmpty() }
|
||||
}
|
||||
}
|
||||
|
||||
internal object VideoCallDeclineClient {
|
||||
private const val TAG = "VideoCallDecline"
|
||||
private const val TIMEOUT_MS = 4_000
|
||||
|
||||
fun send(context: Context, handle: String?, extra: Map<*, *>?) {
|
||||
val fields = VideoCallDeclineRequestFactory.fields(handle, extra)
|
||||
val baseUrl = FlutterSharedPrefs.string(context, "apiBaseUrl")
|
||||
?: FlutterSharedPrefs.string(context, "customBaseUrl")
|
||||
val request = VideoCallDeclineRequestFactory.build(
|
||||
baseUrl = baseUrl,
|
||||
token = FlutterSharedPrefs.string(context, "token"),
|
||||
hwId = FlutterSharedPrefs.string(context, "eatvio.android_install_hw_id"),
|
||||
fields = fields,
|
||||
)
|
||||
if (request == null) {
|
||||
Log.w(
|
||||
TAG,
|
||||
"skip decline POST conversation=${fields.conversationUuid} ended=${fields.endedPush}",
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
val code = post(request)
|
||||
Log.i(TAG, "decline POST status=$code conversation=${fields.conversationUuid}")
|
||||
} catch (error: Exception) {
|
||||
Log.w(TAG, "decline POST failed conversation=${fields.conversationUuid}", error)
|
||||
}
|
||||
}
|
||||
|
||||
private fun post(request: VideoCallDeclineRequest): Int {
|
||||
val connection = (URL(request.url).openConnection() as HttpURLConnection).apply {
|
||||
requestMethod = "POST"
|
||||
connectTimeout = TIMEOUT_MS
|
||||
readTimeout = TIMEOUT_MS
|
||||
doOutput = true
|
||||
setRequestProperty("Authorization", "Bearer ${request.token}")
|
||||
setRequestProperty("Accept", "application/json")
|
||||
setRequestProperty("Content-Type", "application/json; charset=utf-8")
|
||||
}
|
||||
try {
|
||||
connection.outputStream.use { stream ->
|
||||
stream.write(request.body.toByteArray(Charsets.UTF_8))
|
||||
}
|
||||
val code = connection.responseCode
|
||||
val response = if (code in 200..299) connection.inputStream else connection.errorStream
|
||||
response?.use { stream -> stream.readBytes() }
|
||||
return code
|
||||
} finally {
|
||||
connection.disconnect()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package com.eatvioapp.app
|
||||
|
||||
import android.content.Context
|
||||
import android.os.Bundle
|
||||
import android.util.Log
|
||||
import androidx.core.os.BundleCompat
|
||||
import com.hiennv.flutter_callkit_incoming.CallkitConstants
|
||||
import com.hiennv.flutter_callkit_incoming.CallkitEventCallback
|
||||
import com.hiennv.flutter_callkit_incoming.FlutterCallkitIncomingPlugin
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import kotlinx.coroutines.withTimeoutOrNull
|
||||
|
||||
/**
|
||||
* Sends `POST /video-call/decline` from the process that handled the tap.
|
||||
*
|
||||
* The notification Decline button is an explicit broadcast into the CallKit
|
||||
* plugin. That broadcast starts the process when the app was killed and does
|
||||
* not start Flutter. The plugin notifies this callback before it returns, so
|
||||
* the request can finish while the process is still alive.
|
||||
*/
|
||||
object VideoCallDeclineReporter : CallkitEventCallback {
|
||||
private const val TAG = "VideoCallDecline"
|
||||
private const val WAIT_FOR_HTTP_MS = 9_000L
|
||||
|
||||
@Volatile
|
||||
private var appContext: Context? = null
|
||||
|
||||
@Volatile
|
||||
private var installed = false
|
||||
|
||||
fun install(context: Context) {
|
||||
if (installed) return
|
||||
installed = true
|
||||
appContext = context.applicationContext
|
||||
FlutterCallkitIncomingPlugin.registerEventCallback(this)
|
||||
Log.i(TAG, "installed")
|
||||
}
|
||||
|
||||
override fun onCallEvent(event: CallkitEventCallback.CallEvent, callData: Bundle) {
|
||||
if (event != CallkitEventCallback.CallEvent.DECLINE) return
|
||||
val context = appContext ?: return
|
||||
val handle = callData.getString(CallkitConstants.EXTRA_CALLKIT_HANDLE)
|
||||
val extra = copyExtra(callData)
|
||||
if (MainActivity.isInForeground) {
|
||||
CoroutineScope(Dispatchers.IO).launch {
|
||||
VideoCallDeclineClient.send(context, handle, extra)
|
||||
}
|
||||
return
|
||||
}
|
||||
// The Decline button starts this process and then the broadcast ends.
|
||||
// Wait here so Android does not kill the process before the POST returns.
|
||||
runBlocking(Dispatchers.IO) {
|
||||
withTimeoutOrNull(WAIT_FOR_HTTP_MS) {
|
||||
VideoCallDeclineClient.send(context, handle, extra)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun copyExtra(callData: Bundle): Map<String, Any?> {
|
||||
val raw = BundleCompat.getSerializable(
|
||||
callData,
|
||||
CallkitConstants.EXTRA_CALLKIT_EXTRA,
|
||||
HashMap::class.java,
|
||||
) ?: return emptyMap()
|
||||
return buildMap {
|
||||
for ((key, value) in raw) {
|
||||
if (key is String) put(key, value)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
package com.eatvioapp.app
|
||||
|
||||
/**
|
||||
* Body of `POST /api/v2/chat/{conversation}/video-call/decline`.
|
||||
*
|
||||
* [callId] is omitted when it is missing, not a uuid, or equal to the
|
||||
* conversation uuid: the server treats `call_id` as the session uuid.
|
||||
*/
|
||||
internal data class VideoCallDeclineRequest(
|
||||
val url: String,
|
||||
val token: String,
|
||||
val body: String,
|
||||
)
|
||||
|
||||
internal data class VideoCallDeclineFields(
|
||||
val conversationUuid: String,
|
||||
val callId: String?,
|
||||
val endedPush: Boolean,
|
||||
)
|
||||
|
||||
internal object VideoCallDeclineRequestFactory {
|
||||
private val HEX = "0123456789ABCDEF".toCharArray()
|
||||
private val uuidPattern =
|
||||
Regex("^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$")
|
||||
|
||||
fun fields(handle: String?, extra: Map<*, *>?): VideoCallDeclineFields {
|
||||
val conversation = firstString(
|
||||
extra,
|
||||
listOf("conversationUuid", "conversation_uuid"),
|
||||
) ?: handle?.trim().orEmpty()
|
||||
val rawCallId = firstString(extra, listOf("call_id", "callId"))
|
||||
return VideoCallDeclineFields(
|
||||
conversationUuid = conversation,
|
||||
callId = backendCallId(rawCallId, conversation),
|
||||
endedPush = marksEndedPush(extra),
|
||||
)
|
||||
}
|
||||
|
||||
fun build(
|
||||
baseUrl: String?,
|
||||
token: String?,
|
||||
hwId: String?,
|
||||
fields: VideoCallDeclineFields,
|
||||
): VideoCallDeclineRequest? {
|
||||
if (fields.endedPush) return null
|
||||
val conversation = fields.conversationUuid.trim()
|
||||
val authToken = token?.trim().orEmpty()
|
||||
val deviceId = hwId?.trim().orEmpty()
|
||||
val root = baseUrl?.trim()?.trimEnd('/').orEmpty()
|
||||
if (conversation.isEmpty() || authToken.isEmpty()) return null
|
||||
if (deviceId.length < 8 || deviceId.length > 64) return null
|
||||
if (!root.startsWith("http://") && !root.startsWith("https://")) return null
|
||||
|
||||
val encoded = encodePathSegment(conversation)
|
||||
return VideoCallDeclineRequest(
|
||||
url = "$root/api/v2/chat/$encoded/video-call/decline",
|
||||
token = authToken,
|
||||
body = jsonBody(deviceId, fields.callId),
|
||||
)
|
||||
}
|
||||
|
||||
private fun backendCallId(callId: String?, conversationUuid: String): String? {
|
||||
val id = callId?.trim().orEmpty()
|
||||
if (!uuidPattern.matches(id)) return null
|
||||
if (id.equals(conversationUuid.trim(), ignoreCase = true)) return null
|
||||
return id
|
||||
}
|
||||
|
||||
private fun firstString(extra: Map<*, *>?, keys: List<String>): String? {
|
||||
if (extra == null) return null
|
||||
for (key in keys) {
|
||||
val value = extra[key] as? String ?: continue
|
||||
val trimmed = value.trim()
|
||||
if (trimmed.isNotEmpty()) return trimmed
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
private fun marksEndedPush(extra: Map<*, *>?): Boolean {
|
||||
val value = extra?.get("endedPush") ?: return false
|
||||
return when (value) {
|
||||
is Boolean -> value
|
||||
is Number -> value.toInt() != 0
|
||||
is String -> {
|
||||
val normalized = value.trim().lowercase()
|
||||
normalized == "true" || normalized == "1"
|
||||
}
|
||||
else -> false
|
||||
}
|
||||
}
|
||||
|
||||
private fun jsonBody(hwId: String, callId: String?): String {
|
||||
val hw = jsonString(hwId)
|
||||
if (callId == null) return """{"hw_id":$hw}"""
|
||||
return """{"hw_id":$hw,"call_id":${jsonString(callId)}}"""
|
||||
}
|
||||
|
||||
private fun encodePathSegment(value: String): String {
|
||||
val bytes = value.encodeToByteArray()
|
||||
return buildString(bytes.size) {
|
||||
for (byte in bytes) {
|
||||
val code = byte.toInt() and 0xFF
|
||||
val allowed = code in 'A'.code..'Z'.code ||
|
||||
code in 'a'.code..'z'.code ||
|
||||
code in '0'.code..'9'.code ||
|
||||
code == '-'.code ||
|
||||
code == '_'.code ||
|
||||
code == '.'.code ||
|
||||
code == '~'.code
|
||||
if (allowed) {
|
||||
append(code.toChar())
|
||||
} else {
|
||||
append('%')
|
||||
append(HEX[code ushr 4])
|
||||
append(HEX[code and 0x0F])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun jsonString(value: String): String {
|
||||
val escaped = buildString {
|
||||
for (char in value) {
|
||||
when (char) {
|
||||
'\\' -> append("\\\\")
|
||||
'"' -> append("\\\"")
|
||||
'\n' -> append("\\n")
|
||||
'\r' -> append("\\r")
|
||||
'\t' -> append("\\t")
|
||||
else -> append(char)
|
||||
}
|
||||
}
|
||||
}
|
||||
return "\"$escaped\""
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package com.eatvioapp.app
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class VideoCallDeclineRequestTest {
|
||||
private val baseUrl = "https://eatvio.example"
|
||||
private val token = "sanctum-token"
|
||||
private val hwId = "install-hw-id-01"
|
||||
private val conversation = "11111111-1111-1111-1111-111111111111"
|
||||
private val callId = "22222222-2222-2222-2222-222222222222"
|
||||
|
||||
@Test
|
||||
fun buildsDeclinePostWithCallId() {
|
||||
val request = request(callId = callId)
|
||||
|
||||
assertEquals(
|
||||
"https://eatvio.example/api/v2/chat/$conversation/video-call/decline",
|
||||
request?.url,
|
||||
)
|
||||
assertEquals(token, request?.token)
|
||||
assertEquals(
|
||||
"""{"hw_id":"$hwId","call_id":"$callId"}""",
|
||||
request?.body,
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun omitsCallIdWhenItIsTheConversationUuid() {
|
||||
val request = request(callId = conversation.uppercase())
|
||||
|
||||
assertEquals("""{"hw_id":"$hwId"}""", request?.body)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun omitsCallIdThatIsNotAUuid() {
|
||||
val request = request(callId = "message-15")
|
||||
|
||||
assertEquals("""{"hw_id":"$hwId"}""", request?.body)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun readsConversationFromHandleWhenExtraHasNone() {
|
||||
val fields = VideoCallDeclineRequestFactory.fields(conversation, emptyMap<String, Any?>())
|
||||
val request = VideoCallDeclineRequestFactory.build(baseUrl, token, hwId, fields)
|
||||
|
||||
assertTrue(request?.url?.contains(conversation) == true)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun skipsEndedPush() {
|
||||
val fields = VideoCallDeclineRequestFactory.fields(
|
||||
conversation,
|
||||
mapOf("conversationUuid" to conversation, "endedPush" to true),
|
||||
)
|
||||
|
||||
assertNull(VideoCallDeclineRequestFactory.build(baseUrl, token, hwId, fields))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun skipsMissingTokenBaseUrlOrShortHwId() {
|
||||
val fields = VideoCallDeclineRequestFactory.fields(
|
||||
null,
|
||||
mapOf("conversationUuid" to conversation, "call_id" to callId),
|
||||
)
|
||||
|
||||
assertNull(VideoCallDeclineRequestFactory.build(null, token, hwId, fields))
|
||||
assertNull(VideoCallDeclineRequestFactory.build(baseUrl, " ", hwId, fields))
|
||||
assertNull(VideoCallDeclineRequestFactory.build(baseUrl, token, "short", fields))
|
||||
assertNull(VideoCallDeclineRequestFactory.build("eatvio.example", token, hwId, fields))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun trimsATrailingSlashOnTheBaseUrl() {
|
||||
val request = VideoCallDeclineRequestFactory.build(
|
||||
"$baseUrl/",
|
||||
token,
|
||||
hwId,
|
||||
VideoCallDeclineRequestFactory.fields(
|
||||
null,
|
||||
mapOf("conversationUuid" to conversation),
|
||||
),
|
||||
)
|
||||
|
||||
assertEquals(
|
||||
"https://eatvio.example/api/v2/chat/$conversation/video-call/decline",
|
||||
request?.url,
|
||||
)
|
||||
}
|
||||
|
||||
private fun request(callId: String?): VideoCallDeclineRequest? {
|
||||
val fields = VideoCallDeclineRequestFactory.fields(
|
||||
null,
|
||||
mapOf(
|
||||
"conversationUuid" to conversation,
|
||||
"call_id" to callId,
|
||||
),
|
||||
)
|
||||
return VideoCallDeclineRequestFactory.build(baseUrl, token, hwId, fields)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user