| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417 |
- package com.example.modifier.service
- import android.accessibilityservice.AccessibilityService
- import android.accessibilityservice.AccessibilityServiceInfo
- import android.annotation.SuppressLint
- import android.content.ComponentName
- import android.content.Context
- import android.content.Intent
- import android.graphics.PixelFormat
- import android.graphics.Rect
- import android.net.Uri
- import android.os.Build
- import android.os.Handler
- import android.os.Looper
- import android.text.TextUtils
- import android.util.Base64
- import android.util.DisplayMetrics
- import android.util.Log
- import android.view.Gravity
- import android.view.LayoutInflater
- import android.view.MotionEvent
- import android.view.View
- import android.view.View.OnTouchListener
- import android.view.WindowManager
- import android.view.accessibility.AccessibilityEvent
- import android.view.accessibility.AccessibilityNodeInfo
- import android.widget.CompoundButton
- import android.widget.FrameLayout
- import androidx.core.content.ContextCompat
- import androidx.datastore.core.DataStore
- import androidx.datastore.preferences.core.Preferences
- import androidx.datastore.preferences.preferencesDataStore
- import androidx.lifecycle.MediatorLiveData
- import androidx.lifecycle.MutableLiveData
- import androidx.lifecycle.Observer
- import androidx.lifecycle.liveData
- import com.example.modifier.BuildConfig
- import com.example.modifier.CMD_BACK
- import com.example.modifier.CMD_CONVERSATION_LIST_ACTIVITY
- import com.example.modifier.CMD_KILL_GMS
- import com.example.modifier.CMD_KILL_MESSAGING_APP
- import com.example.modifier.CMD_MESSAGING_APP
- import com.example.modifier.CMD_RCS_SETTINGS_ACTIVITY
- import com.example.modifier.Global
- import com.example.modifier.Global.backup
- import com.example.modifier.Global.load
- import com.example.modifier.Global.resetAll
- import com.example.modifier.R
- import com.example.modifier.TraverseResult
- import com.example.modifier.Utils
- import com.example.modifier.data.AppDatabase
- import com.example.modifier.data.BackupItemDao
- import com.example.modifier.databinding.FloatingWindowBinding
- import com.example.modifier.enums.RcsConfigureState
- import com.example.modifier.enums.RcsConnectionStatus
- import com.example.modifier.http.KtorClient
- import com.example.modifier.http.api.DeviceApi
- import com.example.modifier.http.api.RcsNumberApi
- import com.example.modifier.http.api.SysConfigApi
- import com.example.modifier.http.request.RcsNumberRequest
- import com.example.modifier.http.response.DeviceResponse
- import com.example.modifier.http.response.RcsNumberResponse
- import com.example.modifier.http.response.SysConfigResponse
- import com.example.modifier.model.SocketCallback
- import com.example.modifier.model.TaskAction
- import com.example.modifier.model.TaskExecutionResult
- import com.example.modifier.model.TelephonyConfig
- import com.example.modifier.serializer.Json
- import com.example.modifier.ui.shellRun
- import com.google.android.material.color.DynamicColors
- import io.ktor.client.call.body
- import io.ktor.client.plugins.resources.get
- import io.ktor.client.plugins.resources.put
- import io.ktor.client.request.setBody
- import io.ktor.http.ContentType
- import io.ktor.http.contentType
- import io.socket.client.IO
- import io.socket.client.Socket
- import io.socket.emitter.Emitter
- import kotlinx.coroutines.CoroutineScope
- import kotlinx.coroutines.Dispatchers
- import kotlinx.coroutines.delay
- import kotlinx.coroutines.isActive
- import kotlinx.coroutines.launch
- import kotlinx.coroutines.suspendCancellableCoroutine
- import kotlinx.coroutines.withContext
- import kotlinx.coroutines.withTimeout
- import kotlinx.coroutines.withTimeoutOrNull
- import kotlinx.serialization.encodeToString
- import org.apache.commons.collections4.queue.CircularFifoQueue
- import org.apache.commons.lang3.RandomStringUtils
- import org.json.JSONException
- import org.json.JSONObject
- import java.time.LocalDateTime
- import java.time.temporal.ChronoUnit
- import java.util.Optional
- import java.util.Timer
- import java.util.concurrent.atomic.AtomicReference
- import java.util.concurrent.locks.ReentrantLock
- import kotlin.coroutines.resume
- import kotlin.math.max
- import kotlin.math.min
- import kotlin.time.Duration
- import kotlin.time.Duration.Companion.hours
- import kotlin.time.Duration.Companion.minutes
- import kotlin.time.Duration.Companion.seconds
- val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "serverConfig")
- @SuppressLint("SetTextI18n")
- class ModifierService : AccessibilityService(), Emitter.Listener {
- companion object {
- private const val TAG = "ModifierService1"
- const val NAME: String = BuildConfig.APPLICATION_ID + ".service.ModifierService"
- @JvmStatic
- var instance: ModifierService? = null
- private set
- }
- private val handler = Handler(Looper.getMainLooper())
- private val mSocketOpts = IO.Options()
- private lateinit var mSocket: Socket
- private lateinit var binding: FloatingWindowBinding
- val lock = ReentrantLock()
- private var canSend: Boolean
- get() {
- return getSharedPreferences(
- BuildConfig.APPLICATION_ID,
- MODE_PRIVATE
- ).getBoolean("canSend", false)
- }
- set(value) {
- getSharedPreferences(BuildConfig.APPLICATION_ID, MODE_PRIVATE).edit()
- .putBoolean("canSend", value).apply()
- reportDeviceStatues()
- }
- private var counter = 0
- private var cleanCount = 0
- private var lastSend = 0L
- private var rcsInterval = 0L
- private var requestNumberInterval = 0L
- private val running = MutableLiveData(false)
- private val requesting = MutableLiveData(false)
- private val preparing = MutableLiveData(false)
- private val checkingConnection = MutableLiveData(false)
- private var currentTaskId = 0
- private var busy = MediatorLiveData<Boolean>().apply {
- addSource(running) {
- value = it || requesting.value!!
- }
- addSource(requesting) {
- value = it || running.value!!
- }
- addSource(preparing) {
- value = it || running.value!!
- }
- addSource(checkingConnection) {
- value = it || running.value!!
- }
- value =
- requesting.value!! || running.value!! || preparing.value!! || checkingConnection.value!!
- }
- private val rcsConfigureState = MutableLiveData(RcsConfigureState.CONFIGURED)
- private var sendCount: Int
- get() {
- return getSharedPreferences(
- BuildConfig.APPLICATION_ID,
- MODE_PRIVATE
- ).getInt("sendCount", 0)
- }
- set(value) {
- getSharedPreferences(BuildConfig.APPLICATION_ID, MODE_PRIVATE).edit()
- .putInt("sendCount", value).apply()
- }
- private var requestNumberCount: Int
- get() {
- return getSharedPreferences(
- BuildConfig.APPLICATION_ID,
- MODE_PRIVATE
- ).getInt("requestNumberCount", 0)
- }
- set(value) {
- getSharedPreferences(BuildConfig.APPLICATION_ID, MODE_PRIVATE).edit()
- .putInt("requestNumberCount", value).apply()
- }
- private val logcat = liveData(Dispatchers.IO) {
- try {
- val logs = CircularFifoQueue<String>(128)
- val p = Runtime.getRuntime().exec("su")
- p.outputStream.bufferedWriter().use { writer ->
- writer.write("logcat -c")
- writer.newLine()
- writer.flush()
- writer.write("logcat BugleRcsEngine:D *:S -v time")
- writer.newLine()
- writer.flush()
- }
- p.inputStream
- .bufferedReader()
- .useLines { lines ->
- lines.forEach { line ->
- if (line.contains("destState=CheckPreconditionsState")) {
- rcsConfigureState.postValue(RcsConfigureState.NOT_CONFIGURED)
- } else if (line.contains("destState=ReadyState")) {
- rcsConfigureState.postValue(RcsConfigureState.READY)
- } else if (line.contains("destState=WaitingForOtpState")) {
- rcsConfigureState.postValue(RcsConfigureState.WAITING_FOR_OTP)
- } else if (line.contains("destState=VerifyOtpState")) {
- rcsConfigureState.postValue(RcsConfigureState.VERIFYING_OTP)
- } else if (line.contains("destState=ConfiguredState")) {
- rcsConfigureState.postValue(RcsConfigureState.CONFIGURED)
- } else if (line.contains("destState=WaitingForRcsDefaultOnState")) {
- rcsConfigureState.postValue(RcsConfigureState.WAITING_FOR_DEFAULT_ON)
- } else if (line.contains("destState=WaitingForGoogleTosState")) {
- rcsConfigureState.postValue(RcsConfigureState.WAITING_FOR_TOS)
- } else if (line.contains("destState=RetryState")) {
- rcsConfigureState.postValue(RcsConfigureState.RETRY)
- } else if (line.contains("destState=ReplayRequestState")) {
- rcsConfigureState.postValue(RcsConfigureState.REPLAY_REQUEST)
- }
- Regex("(?<time>\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}.\\d{3}) I/BugleRcsEngine\\(\\W*\\d+\\): (?<log>.*)").matchEntire(
- line
- )?.apply {
- val time = groups["time"]?.value?.dropLast(4)
- val log = groups["log"]?.value
- ?.replace(Regex("\\[\\w+-\\w+-\\w+-\\w+-\\w+]"), "")
- ?.replace(Regex("\\[CONTEXT.*]"), "")
- ?.trim()
- if (time != null && log != null) {
- if (log.contains("destState=")) {
- logs.add("$time: $log")
- emit(logs.joinToString("\n"))
- delay(100)
- emit(logs.joinToString("\n"))
- }
- }
- }
- }
- }
- } catch (e: Exception) {
- e.printStackTrace()
- }
- }
- private val backupItemDao: BackupItemDao by lazy {
- AppDatabase.getDatabase(this).itemDao()
- }
- private var requestMode = 1;
- private var currentActivity = ""
- fun connect() {
- try {
- load()
- if (this@ModifierService::binding.isInitialized) {
- binding.swSend.text = Global.name
- }
- if (this@ModifierService::mSocket.isInitialized) {
- mSocket.disconnect()
- }
- mSocketOpts.query =
- "model=${Build.MANUFACTURER} ${Build.MODEL}&name=${Global.name}&id=${Utils.getUniqueID()}"
- mSocketOpts.transports = arrayOf("websocket")
- Log.i(TAG, "Connection query: ${mSocketOpts.query}")
- mSocket = IO.socket(Global.serverUrl, mSocketOpts)
- mSocket.on("message", this@ModifierService)
- mSocket.on(Socket.EVENT_CONNECT) {
- Log.i(TAG, "Connected to server")
- CoroutineScope(Dispatchers.IO).launch {
- delay(500)
- reportDeviceStatues()
- }
- }
- mSocket.on(Socket.EVENT_DISCONNECT) {
- Log.i(TAG, "Disconnected from server")
- }
- mSocket.on(Socket.EVENT_CONNECT_ERROR) { args ->
- Log.i(TAG, "Connection error: " + args[0])
- if (args[0] is Exception) {
- val e = args[0] as Exception
- e.printStackTrace()
- }
- }
- mSocket.connect()
- } catch (e: Exception) {
- e.printStackTrace()
- }
- }
- override fun onCreate() {
- super.onCreate()
- Log.i(TAG, "Starting ModifierService")
- CoroutineScope(Dispatchers.IO).launch {
- preparing.postValue(true)
- if (Global.rebooted()) {
- delay(2.minutes)
- } else {
- delay(5000)
- }
- if (Global.hasRoot()) {
- Global.setupSystem()
- if (Build.MODEL.startsWith("SM-F707") || Build.MODEL.startsWith("SM-F711")) {
- Global.killPhoneProcess(force = false)
- }
- }
- preparing.postValue(false)
- }
- connect()
- val timer = Timer()
- timer.schedule(object : java.util.TimerTask() {
- override fun run() {
- reportDeviceStatues()
- }
- }, 0, 3000)
- }
- override fun onAccessibilityEvent(event: AccessibilityEvent) {
- if (event.eventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
- if (event.packageName != null && event.className != null) {
- val componentName = ComponentName(
- event.packageName.toString(),
- event.className.toString()
- )
- try {
- packageManager.getActivityInfo(componentName, 0)
- currentActivity = componentName.flattenToShortString()
- Log.d(TAG, "Activity: $currentActivity")
- } catch (_: Exception) {
- }
- }
- }
- }
- override fun onInterrupt() {
- }
- override fun call(vararg args: Any) {
- if (args.isNotEmpty()) {
- Log.i(TAG, "Received message: " + args[0])
- if (args[0] is JSONObject) {
- val json = args[0] as JSONObject
- val action = json.optString("action")
- if ("send" == action) {
- val data = json.optJSONObject("data")
- if (data != null) {
- val to = data.optString("to")
- val body = data.optString("body")
- CoroutineScope(Dispatchers.IO).launch {
- send(to, body, 2000)
- }
- }
- } else if ("task" == action) {
- val taskAction = Json.decodeFromString<TaskAction>(json.toString())
- CoroutineScope(Dispatchers.IO).launch {
- runTask(taskAction)
- }
- }
- }
- }
- }
- private suspend fun runTask(taskAction: TaskAction) {
- if (checkingConnection.value!! || running.value!! || preparing.value!! || requesting.value!!) {
- mSocket.emit(
- "callback",
- JSONObject(
- Json.encodeToString(
- SocketCallback<String>(
- id = taskAction.id,
- status = -1,
- error = "another task is running"
- )
- )
- )
- )
- return
- }
- try {
- val rcsWait = taskAction.data.config.rcsWait
- cleanCount = taskAction.data.config.cleanCount
- rcsInterval = taskAction.data.config.rcsInterval
- requestNumberInterval = taskAction.data.config.requestNumberInterval
- currentTaskId = taskAction.data.taskId
- requestMode = if (taskAction.data.config.useBackup) 2 else 1
- if (taskAction.data.config.checkConnection) {
- checkingConnection.postValue(true)
- if (!checkRcsAvailability()) {
- mSocket.emit(
- "callback",
- JSONObject(
- Json.encodeToString(
- SocketCallback<String>(
- id = taskAction.id,
- status = -1,
- error = "RCS not available"
- )
- )
- )
- )
- requestNumber()
- checkingConnection.postValue(false)
- return
- }
- checkingConnection.postValue(false)
- }
- running.postValue(true)
- val success = ArrayList<Int>()
- val fail = ArrayList<Int>()
- for (i in 0 until taskAction.data.tasks.size) {
- val taskItem = taskAction.data.tasks[i]
- try {
- if (send(taskItem.number, taskItem.message, rcsWait)) {
- success.add(taskItem.id)
- } else {
- fail.add(taskItem.id)
- }
- } catch (e: Exception) {
- Log.e(TAG, "runTaskError: ${e.message}", e)
- fail.add(taskItem.id)
- }
- }
- Utils.runAsRoot(CMD_BACK)
- mSocket.emit(
- "callback",
- JSONObject(
- Json.encodeToString(
- SocketCallback(
- id = taskAction.id,
- status = 0,
- data = TaskExecutionResult(success, fail)
- )
- )
- )
- )
- if (requestNumberInterval in 1..sendCount) {
- delay(3000)
- requestNumber()
- } else if (cleanCount in 1..counter) {
- delay(3000)
- Global.clearConv();
- Utils.runAsRoot(CMD_MESSAGING_APP)
- delay(3000)
- counter = 0
- } else {
- delay(2000)
- }
- running.postValue(false)
- } catch (e: Exception) {
- Log.e(TAG, "runTaskError: ${e.message}", e)
- mSocket.emit(
- "callback",
- JSONObject(
- Json.encodeToString(
- SocketCallback<String>(
- id = taskAction.id,
- status = -1,
- error = e.message
- )
- )
- )
- )
- running.postValue(false)
- }
- }
- private fun smsIntent(to: String, body: String): Intent {
- val intent = Intent(Intent.ACTION_SENDTO)
- intent.data = Uri.parse("sms:$to")
- intent.putExtra("sms_body", body)
- intent.putExtra("exit_on_sent", true)
- intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
- intent.setPackage("com.google.android.apps.messaging")
- return intent
- }
- private suspend fun send(to: String, body: String, rcsWait: Long): Boolean {
- Log.i(TAG, "Sending SMS to $to: $body")
- startActivity(smsIntent(to, body))
- try {
- Log.i(TAG, "Command executed successfully, waiting for app to open...")
- delay(1000)
- var success = false
- withTimeoutOrNull(rcsWait) {
- while (true) {
- val root = rootInActiveWindow
- val traverseResult = TraverseResult()
- traverseNode(root, traverseResult)
- if (traverseResult.isRcsCapable) {
- if (traverseResult.sendBtn == null) {
- Log.i(TAG, "Send button not found")
- } else {
- Log.i(TAG, "Clicking send button")
- val dt = System.currentTimeMillis() - lastSend
- if (rcsInterval > 0 && dt < rcsInterval) {
- Log.i(TAG, "Waiting for RCS interval")
- delay(rcsInterval - dt)
- }
- traverseResult.sendBtn!!.performAction(AccessibilityNodeInfo.ACTION_CLICK)
- lastSend = System.currentTimeMillis()
- success = true
- sendCount++
- break
- }
- } else {
- Log.i(TAG, "RCS not detected")
- }
- delay(200)
- }
- }
- counter++
- Log.i(
- TAG,
- "sendCount: $sendCount, Counter: $counter, cleanCount: $cleanCount, requestNumberInterval: $requestNumberInterval"
- )
- delay(1000)
- return success
- } catch (e: Exception) {
- e.printStackTrace()
- }
- return false
- }
- fun getNodes(node: AccessibilityNodeInfo? = null): List<AccessibilityNodeInfo> {
- fun traverseChildren(node: AccessibilityNodeInfo): List<AccessibilityNodeInfo> {
- val result = mutableListOf<AccessibilityNodeInfo>()
- for (i in 0 until node.childCount) {
- val child = node.getChild(i)
- result.add(child)
- result.addAll(traverseChildren(child))
- }
- return result
- }
- return traverseChildren(node ?: rootInActiveWindow)
- }
- private fun traverseNode(node: AccessibilityNodeInfo?, result: TraverseResult) {
- if (node == null) {
- return
- }
- val packageInfo = packageManager.getPackageInfo(
- node.packageName.toString(), 0
- )
- val className = node.className.toString()
- val name = node.viewIdResourceName
- val text = Optional.ofNullable(node.text).map { obj: CharSequence -> obj.toString() }
- .orElse(null)
- val id = node.viewIdResourceName
- Log.d(TAG, "Node: class=$className, text=$text, name=$name, id=$id")
- if ("Compose:Draft:Send" == name) {
- result.sendBtn = node
- }
- if ("com.google.android.apps.messaging:id/send_message_button_icon" == id) {
- result.sendBtn = node
- }
- if (text != null && (text.contains("RCS 聊天") || text.contains("RCS chat"))) {
- result.isRcsCapable = true
- }
- if ("com.google.android.apps.messaging:id/tombstone_message" == id) {
- result.isRcsCapable = text.contains("聊天") || text.contains("Chatting with")
- }
- if (text != null && (text.contains("Turn on RCS chats") || text.contains("开启 RCS 聊天功能")
- || text.contains("Enable chat features") || text.contains("启用聊天功能"))
- ) {
- fun findSwitch(node: AccessibilityNodeInfo): Boolean {
- if ("com.google.android.apps.messaging:id/switchWidget" == node.viewIdResourceName) {
- result.rcsSwitch = node
- return true
- }
- for (i in 0 until node.childCount) {
- val child = node.getChild(i)
- if (findSwitch(child)) {
- return true
- }
- }
- return false
- }
- findSwitch(node.parent.parent)
- }
- if ("com.google.android.apps.messaging:id/rcs_sim_status_status_text" == id) {
- if (text.lowercase().contains("connected") || text.lowercase().contains("已连接")) {
- result.rcsConnectionStatus = RcsConnectionStatus.CONNECTED
- }
- }
- if ("android:id/title" == id) {
- when (text) {
- "状态:已连接" -> result.rcsConnectionStatus = RcsConnectionStatus.CONNECTED
- "Status: Connected" -> result.rcsConnectionStatus = RcsConnectionStatus.CONNECTED
- }
- }
- if (node.childCount != 0) {
- for (i in 0 until node.childCount) {
- traverseNode(node.getChild(i), result)
- }
- }
- }
- @SuppressLint("ClickableViewAccessibility")
- override fun onServiceConnected() {
- super.onServiceConnected()
- instance = this
- val info = AccessibilityServiceInfo()
- info.flags = AccessibilityServiceInfo.DEFAULT or
- AccessibilityServiceInfo.FLAG_REPORT_VIEW_IDS or
- AccessibilityServiceInfo.FLAG_INCLUDE_NOT_IMPORTANT_VIEWS
- info.eventTypes = AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
- info.feedbackType = AccessibilityServiceInfo.FEEDBACK_SPOKEN
- info.notificationTimeout = 100
- this.serviceInfo = info
- val displayMetrics = DisplayMetrics()
- val windowManager = getSystemService(WINDOW_SERVICE) as WindowManager
- windowManager.defaultDisplay.getMetrics(displayMetrics)
- val height = displayMetrics.heightPixels
- val width = displayMetrics.widthPixels
- val mLayout = FrameLayout(this)
- val layoutParams = WindowManager.LayoutParams()
- layoutParams.type = WindowManager.LayoutParams.TYPE_ACCESSIBILITY_OVERLAY
- layoutParams.format = PixelFormat.TRANSLUCENT
- layoutParams.flags = layoutParams.flags or WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
- layoutParams.flags = layoutParams.flags or WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
- layoutParams.width = WindowManager.LayoutParams.WRAP_CONTENT
- layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT
- layoutParams.x = 0
- layoutParams.y = 800
- layoutParams.gravity = Gravity.START or Gravity.TOP
- val newContext = DynamicColors.wrapContextIfAvailable(applicationContext, R.style.AppTheme)
- val inflater = LayoutInflater.from(newContext)
- binding = FloatingWindowBinding.inflate(inflater, mLayout, true)
- binding.swSend.text = Global.name
- binding.tvVersion.text = "v${BuildConfig.VERSION_CODE}"
- windowManager.addView(mLayout, layoutParams)
- var maxX = 0
- var maxY = 0
- binding.root.measure(View.MeasureSpec.EXACTLY, View.MeasureSpec.EXACTLY)
- binding.root.post {
- maxX = width - binding.root.measuredWidth
- maxY = height - binding.root.measuredHeight
- Log.i(TAG, "measured: $maxX, $maxY")
- layoutParams.x = maxX
- windowManager.updateViewLayout(mLayout, layoutParams)
- }
- val downX = AtomicReference(0f)
- val downY = AtomicReference(0f)
- val downParamX = AtomicReference(0)
- val downParamY = AtomicReference(0)
- val touchListener = OnTouchListener { v, event ->
- when (event.action) {
- MotionEvent.ACTION_DOWN -> {
- downX.set(event.rawX)
- downY.set(event.rawY)
- downParamX.set(layoutParams.x)
- downParamY.set(layoutParams.y)
- }
- MotionEvent.ACTION_MOVE -> {
- layoutParams.x = min(
- max((downParamX.get() + (event.rawX - downX.get())).toDouble(), 0.0),
- maxX.toDouble()
- )
- .toInt()
- layoutParams.y = min(
- max((downParamY.get() + (event.rawY - downY.get())).toDouble(), 0.0),
- maxY.toDouble()
- )
- .toInt()
- windowManager.updateViewLayout(mLayout, layoutParams)
- }
- MotionEvent.ACTION_UP -> {
- return@OnTouchListener event.eventTime - event.downTime >= 200
- }
- }
- false
- }
- binding.swSend.setOnTouchListener(touchListener)
- binding.swConnect.isChecked = true
- binding.swConnect.setOnCheckedChangeListener { buttonView: CompoundButton?, isChecked: Boolean ->
- if (isChecked) {
- connect()
- } else {
- if (this::mSocket.isInitialized) {
- mSocket.disconnect()
- }
- }
- }
- binding.swSend.isChecked = canSend
- binding.swSend.setOnCheckedChangeListener { buttonView: CompoundButton?, isChecked: Boolean ->
- canSend = isChecked
- }
- logcat.observeForever {
- binding.tvLog.text = it
- binding.scroll.fullScroll(View.FOCUS_DOWN)
- }
- requesting.observeForever {
- binding.btnReq.isEnabled = !it
- }
- binding.btnReq.setOnClickListener {
- CoroutineScope(Dispatchers.IO).launch {
- requestNumber(reset = false, noBackup = true)
- }
- }
- // binding.btnInspect.setOnClickListener {
- // traverseNode(rootInActiveWindow, TraverseResult())
- // }
- binding.btnReset.setOnClickListener {
- binding.btnReset.isEnabled = false
- CoroutineScope(Dispatchers.IO).launch {
- reset()
- withContext(Dispatchers.Main) {
- binding.btnReset.isEnabled = true
- }
- }
- }
- binding.btnCheck.setOnClickListener {
- CoroutineScope(Dispatchers.IO).launch {
- checkRcsAvailability()
- }
- }
- binding.btnStoreNumbers.setOnClickListener {
- CoroutineScope(Dispatchers.IO).launch {
- storeNumbers()
- }
- }
- binding.btnToggleOn.setOnClickListener {
- binding.btnToggleOn.isEnabled = false
- CoroutineScope(Dispatchers.IO).launch {
- toggleRcsSwitch(true)
- withContext(Dispatchers.Main) {
- binding.btnToggleOn.isEnabled = true
- }
- }
- }
- binding.btnToggleOff.setOnClickListener {
- binding.btnToggleOff.isEnabled = false
- CoroutineScope(Dispatchers.IO).launch {
- toggleRcsSwitch(false)
- withContext(Dispatchers.Main) {
- binding.btnToggleOff.isEnabled = true
- }
- }
- }
- binding.btnClean.setOnClickListener {
- binding.btnClean.isEnabled = false
- CoroutineScope(Dispatchers.IO).launch {
- Global.clearConv()
- withContext(Dispatchers.Main) {
- binding.btnClean.isEnabled = true
- }
- }
- }
- binding.btnChangeProfile.setOnClickListener {
- val intent = Intent()
- intent.action = "com.github.metacubex.clash.meta.action.USE_PROFILE"
- intent.putExtra(
- "base64",
- "bW9kZTogcnVsZQ0KdW5pZmllZC1kZWxheTogdHJ1ZQ0KcHJveGllczoNCiAgLSB7bmFtZTogbWN0dG1uMG4sIHNlcnZlcjogbGFib3JhdG9yeS5tZXNnaXR5LnRvcCwgcG9ydDogMTUxNjYsIHJlYWxpdHktb3B0czoge3B1YmxpYy1rZXk6IE5XRG9UY3pjU1AtaHhJaGhGUXQ4Sl9tOWpDRzU1NGlnRWFPRnI4MUlTeVEsIHNob3J0LWlkOiAzNDAwMjZjNWU2MGV9LCBjbGllbnQtZmluZ2VycHJpbnQ6IGNocm9tZSwgdHlwZTogdmxlc3MsIHV1aWQ6IGJkZTBjNjRkLTFmNDItNDZlZi1hMjA3LTNkMGFkZWUyOWVlOCwgdGxzOiB0cnVlLCB0Zm86IGZhbHNlLCBza2lwLWNlcnQtdmVyaWZ5OiBmYWxzZSwgc2VydmVybmFtZTogeWFob28uY29tLCBuZXR3b3JrOiB0Y3B9DQogIC0gbmFtZTogdmUNCiAgICB0eXBlOiBzb2NrczUNCiAgICBzZXJ2ZXI6IGdsb2JhbC5pcG1veXUuY29tDQogICAgcG9ydDogMzAwMA0KICAgIHVzZXJuYW1lOiBidXllcmV2ZW50XzE3M18wXzBfMTBfVEVTVDAwMDJfMTVfMQ0KICAgIHBhc3N3b3JkOiAxMjM0NTYNCiAgICBkaWFsZXItcHJveHk6IG1jdHRtbjBuDQpwcm94eS1ncm91cHM6DQogIC0gbmFtZTog6IqC54K56YCJ5oupDQogICAgdHlwZTogc2VsZWN0DQogICAgcHJveGllczoNCiAgICAgIC0gdmUNCnJ1bGVzOg0KICAtIERPTUFJTi1TVUZGSVgsaXpvdW1hLmNvbSxESVJFQ1QNCiAgLSBJUC1DSURSLDQ3Ljk4LjIyNS4yOC8zMixESVJFQ1QNCiAgLSBJUC1DSURSLDguMTQ5LjEyOC4yNTEvMzIsRElSRUNUDQogIC0gRE9NQUlOLVNVRkZJWCxiYWlkdS5jb20sRElSRUNUDQogIC0gRE9NQUlOLVNVRkZJWCxhbGl5dW5jcy5jb20sRElSRUNUDQogIC0gR0VPSVAsQ04sRElSRUNUDQogIC0gTUFUQ0gs6IqC54K56YCJ5oup"
- )
- intent.putExtra("name", "ve")
- intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
- startActivity(intent)
- }
- busy.observeForever {
- reportDeviceStatues()
- }
- }
- private fun reportDeviceStatues() {
- if (this::mSocket.isInitialized) {
- val data = JSONObject()
- try {
- data.put("action", "updateDevice")
- val dataObj = JSONObject()
- dataObj.put("canSend", canSend)
- dataObj.put("busy", busy.value)
- data.put("data", dataObj)
- mSocket.emit("message", data)
- } catch (e: JSONException) {
- e.printStackTrace()
- }
- }
- }
- suspend fun waitForRcsState(
- states: Array<RcsConfigureState>,
- timeout: Duration
- ): RcsConfigureState? {
- var state: RcsConfigureState? = null
- withTimeoutOrNull(timeout) {
- withContext(Dispatchers.Main) {
- suspendCancellableCoroutine { continuation ->
- val observer = Observer<RcsConfigureState> { value ->
- if (states.contains(value)) {
- state = value
- if (isActive)
- continuation.resume(Unit)
- }
- }
- rcsConfigureState.observeForever(observer)
- continuation.invokeOnCancellation {
- handler.post {
- Log.i(TAG, "removeObserver")
- rcsConfigureState.removeObserver(observer)
- }
- }
- }
- }
- false
- }
- return state
- }
- suspend fun toggleRcsSwitch(state: Boolean, retry: Int = 3): Boolean {
- val res = TraverseResult()
- shellRun(CMD_RCS_SETTINGS_ACTIVITY, "sleep 0.5")
- val success = run repeatBlock@{
- repeat(retry) {
- res.rcsSwitch = null
- traverseNode(rootInActiveWindow, res)
- if (res.rcsSwitch == null) {
- shellRun(CMD_BACK, "sleep 0.5", CMD_RCS_SETTINGS_ACTIVITY, "sleep 0.5")
- } else {
- if (res.rcsSwitch!!.isChecked == state) {
- return@repeatBlock true
- }
- val rect = Rect()
- res.rcsSwitch!!.getBoundsInScreen(rect)
- if (state) {
- shellRun(
- "input tap ${rect.centerX()} ${rect.centerY()}", "sleep 1",
- )
- if (isOldVersion()) {
- rootInActiveWindow.findAccessibilityNodeInfosByViewId("android:id/button1")
- .firstOrNull()?.performAction(AccessibilityNodeInfo.ACTION_CLICK)
- delay(1000)
- }
- while ("com.google.android.apps.messaging/.ui.appsettings.RcsSettingsActivity" == currentActivity) {
- shellRun(CMD_BACK)
- delay(500)
- }
- shellRun(CMD_RCS_SETTINGS_ACTIVITY, "sleep 1")
- } else {
- shellRun(
- "input tap ${rect.centerX()} ${rect.centerY()}", "sleep 1",
- )
- rootInActiveWindow.findAccessibilityNodeInfosByViewId("android:id/button1")
- .firstOrNull()?.performAction(AccessibilityNodeInfo.ACTION_CLICK)
- delay(1000)
- while ("com.google.android.apps.messaging/.ui.appsettings.RcsSettingsActivity" == currentActivity) {
- shellRun(CMD_BACK)
- delay(500)
- }
- shellRun(CMD_RCS_SETTINGS_ACTIVITY, "sleep 1")
- }
- res.rcsSwitch = null
- traverseNode(rootInActiveWindow, res)
- if (res.rcsSwitch?.isChecked == state) {
- return@repeatBlock true
- }
- }
- }
- false
- }
- while ("com.google.android.apps.messaging/.ui.appsettings.RcsSettingsActivity" == currentActivity) {
- shellRun(CMD_BACK)
- delay(500)
- }
- return success
- }
- private fun isOldVersion(): Boolean {
- val info = packageManager.getPackageInfo("com.google.android.apps.messaging", 0)
- var oldVersion = false
- if (info != null) {
- if (info.versionCode < 170545910) {
- oldVersion = true
- }
- }
- return oldVersion
- }
- private suspend fun reset() {
- if (isOldVersion()) {
- withTimeout(1.hours) {
- while (true) {
- delay(100)
- withContext(Dispatchers.Main) {
- binding.tvLog.text = "Waiting for RCS switch on..."
- }
- rcsConfigureState.postValue(RcsConfigureState.NOT_CONFIGURED)
- Global.saveMock()
- resetAll()
- var switchAppear = waitForRcsState(
- arrayOf(RcsConfigureState.WAITING_FOR_TOS),
- 1.minutes
- )?.let {
- it == RcsConfigureState.WAITING_FOR_TOS
- }
- if (switchAppear != true) {
- shellRun(
- CMD_KILL_GMS, CMD_KILL_MESSAGING_APP, "sleep 1",
- CMD_MESSAGING_APP
- )
- switchAppear = waitForRcsState(
- arrayOf(RcsConfigureState.WAITING_FOR_TOS),
- 2.minutes
- )?.let {
- it == RcsConfigureState.WAITING_FOR_TOS
- }
- if (switchAppear != true) {
- Log.e(TAG, "RCS not entered default on state, retrying...")
- continue
- }
- }
- if (!toggleRcsSwitch(false)) {
- Log.e(TAG, "RCS switch not turned off, retrying...")
- continue
- }
- if (!toggleRcsSwitch(true)) {
- Log.e(TAG, "RCS switch not turned on, retrying...")
- continue
- }
- var resetSuccess = waitForRcsState(
- arrayOf(
- RcsConfigureState.READY
- ), 30.seconds
- ).let { it == RcsConfigureState.READY }
- if (!resetSuccess) {
- toggleRcsSwitch(false)
- delay(1000)
- toggleRcsSwitch(true)
- resetSuccess = waitForRcsState(
- arrayOf(
- RcsConfigureState.READY
- ), 1.minutes
- ).let { it == RcsConfigureState.READY }
- }
- Log.i(TAG, "waitForRcsState: $resetSuccess")
- requestNumberCount = 0
- if (resetSuccess) {
- delay(3000)
- break
- }
- }
- }
- } else {
- withTimeout(1.hours) {
- while (true) {
- delay(100)
- withContext(Dispatchers.Main) {
- binding.tvLog.text = "Waiting for RCS switch on..."
- }
- rcsConfigureState.postValue(RcsConfigureState.NOT_CONFIGURED)
- Global.saveMock()
- resetAll()
- var switchAppear = waitForRcsState(
- arrayOf(RcsConfigureState.WAITING_FOR_DEFAULT_ON),
- 1.minutes
- )?.let {
- it == RcsConfigureState.WAITING_FOR_DEFAULT_ON
- }
- if (switchAppear != true) {
- shellRun(
- CMD_KILL_GMS, CMD_KILL_MESSAGING_APP, "sleep 1",
- CMD_MESSAGING_APP
- )
- switchAppear = waitForRcsState(
- arrayOf(RcsConfigureState.WAITING_FOR_DEFAULT_ON),
- 2.minutes
- )?.let {
- it == RcsConfigureState.WAITING_FOR_DEFAULT_ON
- }
- if (switchAppear != true) {
- Log.e(TAG, "RCS not entered default on state, retrying...")
- continue
- }
- }
- val switchOn = toggleRcsSwitch(true)
- if (!switchOn) {
- Log.e(TAG, "RCS switch not turned on, retrying...")
- continue
- }
- var resetSuccess = waitForRcsState(
- arrayOf(
- RcsConfigureState.READY
- ), 30.seconds
- ).let { it == RcsConfigureState.READY }
- if (!resetSuccess) {
- toggleRcsSwitch(false)
- delay(1000)
- toggleRcsSwitch(true)
- resetSuccess = waitForRcsState(
- arrayOf(
- RcsConfigureState.READY
- ), 1.minutes
- ).let { it == RcsConfigureState.READY }
- }
- Log.i(TAG, "waitForRcsState: $resetSuccess")
- requestNumberCount = 0
- if (resetSuccess) {
- delay(3000)
- break
- }
- }
- }
- }
- }
- private suspend fun requestNumber(
- reset: Boolean = false,
- noBackup: Boolean = false,
- fresh: Boolean = false
- ) {
- val color = ContextCompat.getColorStateList(binding.root.context, R.color.btn_color)
- binding.btnReq.backgroundTintList = color
- if (getSharedPreferences("settings", Context.MODE_PRIVATE)
- .getBoolean("do_not_request", false)
- ) {
- return
- }
- if (requesting.value!!) {
- return
- }
- requesting.postValue(true)
- if (Global.telephonyConfig.available == true) {
- backup(
- backupItemDao = backupItemDao,
- type = "auto",
- sendCount = sendCount,
- fresh = fresh
- )
- }
- requestNumberCount++
- var requestSuccess = false
- var retry = 0
- var needRest = reset
- withTimeoutOrNull(1.hours) {
- while (true) {
- delay(200)
- needRest = needRest || retry > 2 || requestNumberCount > 5
- try {
- val device = KtorClient.get(DeviceApi.Id(id = Utils.getUniqueID()))
- .body<DeviceResponse>()
- val prefs = getSharedPreferences("settings", Context.MODE_PRIVATE)
- if (TextUtils.isEmpty(device.clashProfile)) {
- prefs.edit()
- .remove("clash_profile")
- .apply()
- val intent = Intent()
- intent.action = "com.github.metacubex.clash.meta.action.STOP_CLASH"
- intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
- startActivity(intent)
- } else {
- val oldProfile = prefs.getString("clash_profile", "")
- if (oldProfile != device.clashProfile) {
- prefs.edit()
- .putString("clash_profile", device.clashProfile)
- .apply()
- val intent = Intent()
- intent.action = "com.github.metacubex.clash.meta.action.USE_PROFILE"
- intent.putExtra(
- "base64",
- Base64.encodeToString(
- device.clashProfile!!.toByteArray(),
- Base64.DEFAULT
- )
- )
- intent.putExtra("name", device.pinCountry)
- intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
- startActivity(intent)
- delay(5000)
- }
- }
- if (requestMode == 2 && !noBackup) {
- val backup = backupItemDao.findBackupForRestore(
- Global.telephonyConfig.number,
- System.currentTimeMillis() - 2 * 24 * 60 * 60 * 1000
- )
- if (backup != null) {
- if (Global.restore(backup)) {
- requestSuccess = true
- break
- } else {
- backup(backupItemDao, "auto", 0)
- continue
- }
- }
- }
- if (needRest &&
- !getSharedPreferences("settings", Context.MODE_PRIVATE)
- .getBoolean("do_not_reset", false)
- ) {
- reset()
- retry = 0
- needRest = false
- }
- rcsConfigureState.postValue(RcsConfigureState.NOT_CONFIGURED)
- withContext(Dispatchers.Main) {
- binding.tvLog.text = "Requesting number..."
- }
- val req = RcsNumberRequest(
- deviceId = Utils.getUniqueID(),
- taskId = currentTaskId
- )
- if (!TextUtils.isEmpty(device.pinCountry)) {
- req.country = device.pinCountry
- }
- val response = KtorClient.put(
- RcsNumberApi()
- ) {
- contentType(ContentType.Application.Json)
- setBody(req)
- }
- var rcsNumber = response.body<RcsNumberResponse>()
- Log.i(TAG, "requestNumber response: $rcsNumber")
- withContext(Dispatchers.Main) {
- binding.tvLog.text = "Requesting success, waiting for logs..."
- }
- Global.save(
- TelephonyConfig(
- rcsNumber.number,
- rcsNumber.mcc,
- rcsNumber.mnc,
- Global.genICCID(rcsNumber.mnc, rcsNumber.areaCode),
- rcsNumber.mcc + rcsNumber.mnc + RandomStringUtils.randomNumeric(
- 15 - rcsNumber.mcc.length - rcsNumber.mnc.length
- ),
- Utils.generateIMEI(),
- rcsNumber.country,
- rcsNumber.areaCode
- )
- )
- shellRun(CMD_MESSAGING_APP)
- withContext(Dispatchers.Main) {
- binding.tvLog.text = "Waiting for logs..."
- }
- if (rcsNumber.expiryTime.isBefore(LocalDateTime.now())) {
- Log.e(TAG, "RCS number expired, retrying...")
- continue
- }
- var sendOtpTimeout = ChronoUnit.SECONDS.between(
- LocalDateTime.now(),
- rcsNumber.expiryTime
- ).seconds
- if (sendOtpTimeout < 60.seconds) {
- Log.e(TAG, "OTP timeout too short, retrying...")
- continue
- }
- if (sendOtpTimeout > 2.minutes) {
- sendOtpTimeout = 2.minutes
- }
- if (waitForRcsState(
- arrayOf(RcsConfigureState.WAITING_FOR_OTP),
- sendOtpTimeout
- ) != RcsConfigureState.WAITING_FOR_OTP
- ) {
- if (!toggleRcsSwitch(true)) {
- needRest = true
- }
- if (RcsConfigureState.REPLAY_REQUEST == rcsConfigureState.value) {
- Log.e(TAG, "REPLAY_REQUEST detected, may reset after 3 retry ($retry)")
- retry++
- }
- Log.e(TAG, "RCS not entered waiting for OTP state, retrying...")
- continue
- }
- if (rcsNumber.expiryTime.isBefore(LocalDateTime.now())) {
- Log.e(TAG, "RCS number expired, retrying...")
- continue
- }
- withTimeoutOrNull(60.seconds) {
- while (true) {
- try {
- rcsNumber = KtorClient.get(RcsNumberApi.Id(id = rcsNumber.id))
- .body<RcsNumberResponse>()
- Log.i(TAG, "wait for otp response: $rcsNumber")
- if (rcsNumber.status == RcsNumberResponse.STATUS_SUCCESS || rcsNumber.status == RcsNumberResponse.STATUS_EXPIRED) {
- break
- }
- } catch (exception: Exception) {
- Log.e(TAG, "wait for otp Error: ${exception.stackTrace}")
- }
- delay(2.seconds)
- }
- }
- if (rcsNumber.status != RcsNumberResponse.STATUS_SUCCESS) {
- Log.e(TAG, "OTP not received, retrying...")
- continue
- }
- val match =
- Regex("Your Messenger verification code is G-(\\d{6})")
- .matchEntire(rcsNumber.message!!)
- if (match != null) {
- val otp = match.groupValues[1]
- Log.i(TAG, "OTP: $otp")
- val sender = "3538"
- val msg = "Your Messenger verification code is G-$otp"
- val configured = run configuring@{
- repeat(2) {
- Global.sendSmsIntent(sender, msg)
- val state =
- waitForRcsState(
- arrayOf(
- RcsConfigureState.CONFIGURED,
- RcsConfigureState.RETRY
- ), 60.seconds
- )
- when (state) {
- RcsConfigureState.CONFIGURED -> {
- return@configuring true
- }
- RcsConfigureState.RETRY -> {
- waitForRcsState(
- arrayOf(RcsConfigureState.WAITING_FOR_OTP),
- 60.seconds
- )
- }
- else -> {
- Log.e(TAG, "verifyOtp fail, retrying...")
- }
- }
- }
- false
- }
- if (!configured) {
- Log.e(TAG, "RCS not configured, retrying...")
- continue
- } else {
- requestSuccess = true
- break
- }
- }
- } catch (e: Exception) {
- Log.e(TAG, "requestNumberError: ${e.message}", e)
- }
- }
- }
- if (requestSuccess) {
- Global.telephonyConfig.available = true
- Global.save()
- sendCount = 0
- counter = 0
- Log.i(TAG, "requestNumber success")
- if (isOldVersion()) {
- delay(5000)
- shellRun(CMD_KILL_MESSAGING_APP, "sleep 1", CMD_MESSAGING_APP)
- delay(2000)
- }
- } else {
- Log.e(TAG, "requestNumber failed")
- canSend = false
- withContext(Dispatchers.Main) {
- binding.swSend.isChecked = false
- binding.btnReq.backgroundTintList =
- ContextCompat.getColorStateList(binding.root.context, R.color.btn_color_error)
- }
- }
- requesting.postValue(false)
- }
- private suspend fun checkRcsConnectivity(): Boolean = run checkRcsConnection@{
- repeat(3) {
- Log.i(TAG, "Checking RCS status...")
- shellRun(
- CMD_CONVERSATION_LIST_ACTIVITY,
- CMD_RCS_SETTINGS_ACTIVITY,
- "sleep 1",
- )
- val res = TraverseResult()
- traverseNode(rootInActiveWindow, res)
- if (res.rcsConnectionStatus == RcsConnectionStatus.CONNECTED) {
- Log.i(TAG, "RCS is connected")
- shellRun(CMD_BACK)
- return@checkRcsConnection true
- } else {
- Log.i(TAG, "RCS not connected, retrying...")
- }
- shellRun(CMD_BACK, "sleep ${it * 2}")
- }
- false
- }
- suspend fun checkRcsAvailability(): Boolean {
- checkingConnection.postValue(true)
- val availability = run checkAvailability@{
- val rcsConnected = checkRcsConnectivity()
- if (!rcsConnected) {
- return@checkAvailability false
- }
- var config: SysConfigResponse
- val checkRcsAvailabilityNumbers = mutableListOf<String>()
- withTimeoutOrNull(60.seconds) {
- while (true) {
- try {
- config = KtorClient.get(
- SysConfigApi.Id(
- SysConfigApi(),
- "check_availability_numbers"
- )
- )
- .body<SysConfigResponse>()
- Log.i(TAG, "sysConfig response: $config")
- checkRcsAvailabilityNumbers.addAll(
- config.value.split(",").map { it.trim() })
- break
- } catch (exception: Exception) {
- Log.e(TAG, "sysConfig Error: ${exception.message}", exception)
- }
- delay(1.seconds)
- }
- }
- checkRcsAvailabilityNumbers.forEach {
- startActivity(smsIntent(it, ""))
- val s = withTimeoutOrNull(5.seconds) {
- while (true) {
- val root = rootInActiveWindow
- val traverseResult = TraverseResult()
- traverseNode(root, traverseResult)
- if (traverseResult.isRcsCapable) {
- return@withTimeoutOrNull true
- } else {
- Log.i(TAG, "checkRcsAvailability: RCS not detected")
- }
- delay(200)
- }
- }
- if (s == true) {
- Log.i(TAG, "checkRcsAvailability: $it success")
- delay(1000)
- return@checkAvailability true
- }
- }
- false
- }
- checkingConnection.postValue(false)
- return availability
- }
- private suspend fun storeNumbers() {
- withContext(Dispatchers.Main) {
- binding.btnStoreNumbers.isEnabled = false
- }
- repeat(100) {
- requestNumber(reset = true, fresh = it > 0)
- delay(5000)
- }
- withContext(Dispatchers.Main) {
- binding.btnStoreNumbers.isEnabled = true
- }
- }
- }
|