| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837 |
- package com.example.modifier.service
- import android.accessibilityservice.AccessibilityService
- import android.accessibilityservice.AccessibilityServiceInfo
- import android.annotation.SuppressLint
- 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.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.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.Global
- 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.databinding.FloatingWindowBinding
- import com.example.modifier.enums.RcsConfigureState
- import com.example.modifier.extension.waitUntilValueIs
- import com.example.modifier.http.KtorClient
- import com.example.modifier.http.RcsNumberApi
- import com.example.modifier.http.request.RcsNumberRequest
- import com.example.modifier.http.response.RcsNumberResponse
- import com.example.modifier.model.TelephonyConfig
- 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.runBlocking
- import kotlinx.coroutines.suspendCancellableCoroutine
- import kotlinx.coroutines.withContext
- import kotlinx.coroutines.withTimeout
- import kotlinx.coroutines.withTimeoutOrNull
- import org.apache.commons.collections4.queue.CircularFifoQueue
- import org.apache.commons.lang3.RandomStringUtils
- import org.apache.commons.lang3.StringUtils
- import org.json.JSONArray
- import org.json.JSONException
- import org.json.JSONObject
- import java.util.Optional
- import java.util.concurrent.ScheduledExecutorService
- import java.util.concurrent.ScheduledThreadPoolExecutor
- import java.util.concurrent.TimeUnit
- import java.util.concurrent.atomic.AtomicReference
- import kotlin.coroutines.coroutineContext
- 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 = "ModifierService"
- const val NAME: String = BuildConfig.APPLICATION_ID + ".service.ModifierService"
- @JvmStatic
- var instance: ModifierService? = null
- private set
- }
- private val handler = Handler(Looper.getMainLooper())
- private val mExecutor: ScheduledExecutorService = ScheduledThreadPoolExecutor(8)
- private val mSocketOpts = IO.Options()
- private lateinit var mSocket: Socket
- private lateinit var binding: FloatingWindowBinding
- 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 = 0
- private val running = MutableLiveData(false)
- private val requesting = MutableLiveData(false)
- private var currentTaskId = 0
- private var busy = MediatorLiveData<Boolean>().apply {
- addSource(running) {
- value = it || requesting.value!!
- }
- addSource(requesting) {
- value = it || running.value!!
- }
- value = requesting.value!! || running.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=RetryState")) {
- rcsConfigureState.postValue(RcsConfigureState.RETRY)
- }
- 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()
- }
- }
- 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")
- connect()
- }
- override fun onAccessibilityEvent(event: AccessibilityEvent) {
- // traverseNode(getRootInActiveWindow(), new TraverseResult());
- }
- 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")
- send(to, body, 2000)
- }
- } else if ("task" == action) {
- val data = json.optJSONObject("data")
- val id = json.optString("id")
- if (data != null && StringUtils.isNoneBlank(id)) {
- runTask(id, data)
- }
- } else if ("changeNumber" == action) {
- }
- }
- }
- }
- private fun runTask(id: String, data: JSONObject) {
- val config = data.optJSONObject("config")
- config!!
- val rcsWait = config.optLong("rcsWait", 2000)
- cleanCount = config.optInt("cleanCount", 20)
- rcsInterval = config.optLong("rcsInterval", 0)
- requestNumberInterval = config.optInt("requestNumberInterval", 0)
- val tasks = data.optJSONArray("tasks")!!
- currentTaskId = data.optInt("taskId", 0)
- mExecutor.submit {
- running.postValue(true)
- val success = JSONArray()
- val fail = JSONArray()
- for (i in 0 until tasks.length()) {
- val task = tasks.optJSONObject(i)
- val to = task.optString("number")
- val body = task.optString("message")
- val taskId = task.optInt("id")
- try {
- if (send(to, body, rcsWait)) {
- success.put(taskId)
- } else {
- fail.put(taskId)
- }
- } catch (e: Exception) {
- e.printStackTrace()
- fail.put(taskId)
- }
- }
- val res = JSONObject()
- try {
- res.put("id", id)
- res.put("status", 0)
- res.put(
- "data", JSONObject()
- .put("success", success)
- .put("fail", fail)
- )
- } catch (e: JSONException) {
- }
- mSocket.emit("callback", res)
- if (requestNumberInterval in 1..sendCount) {
- runBlocking {
- requestNumber()
- }
- }
- running.postValue(false)
- }
- }
- private fun send(to: String, body: String, rcsWait: Long): Boolean {
- Log.i(TAG, "Sending SMS to $to: $body")
- val intent = Intent(Intent.ACTION_SENDTO)
- intent.setData(Uri.parse("sms:$to"))
- intent.putExtra("sms_body", body)
- intent.putExtra("exit_on_sent", true)
- intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
- startActivity(intent)
- try {
- Log.i(TAG, "Command executed successfully, waiting for app to open...")
- val f = mExecutor.schedule<Boolean>(
- {
- var success = false
- val ts = System.currentTimeMillis()
- while (System.currentTimeMillis() - ts < rcsWait) {
- val root = rootInActiveWindow
- val packageName = root.packageName.toString()
- 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")
- Thread.sleep(rcsInterval - dt)
- }
- traverseResult.sendBtn.performAction(AccessibilityNodeInfo.ACTION_CLICK)
- lastSend = System.currentTimeMillis()
- success = true
- sendCount++
- break
- }
- } else {
- Log.i(TAG, "RCS not detected")
- }
- try {
- Thread.sleep(500)
- } catch (e: InterruptedException) {
- e.printStackTrace()
- }
- }
- counter++
- Log.i(
- TAG,
- "sendCount: $sendCount, Counter: $counter, cleanCount: $cleanCount, requestNumberInterval: $requestNumberInterval"
- )
- if (cleanCount in 1..counter) {
- counter = 0
- Thread.sleep(2000)
- Global.clearConv();
- Thread.sleep(2000)
- }
- success
- }, 1000, TimeUnit.MILLISECONDS
- )
- synchronized(f) {
- Log.i(TAG, "Waiting for task to complete...")
- return f.get()
- }
- } catch (e: Exception) {
- e.printStackTrace()
- }
- return false
- }
- private fun traverseNode(node: AccessibilityNodeInfo?, result: TraverseResult) {
- if (node == null) {
- return
- }
- 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 (text != null && (text.contains("Turn on RCS chats") || text.contains("开启 RCS 聊天功能"))) {
- 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 (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
- 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
- windowManager.addView(mLayout, layoutParams)
- val maxX = width - binding.root.measuredWidth
- val maxY = height - binding.root.measuredHeight
- 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 {
- requestNumberCount = 6
- CoroutineScope(Dispatchers.IO).launch {
- requestNumber()
- }
- }
- binding.btnInspect.setOnClickListener {
- CoroutineScope(Dispatchers.IO).launch {
- traverseNode(rootInActiveWindow, TraverseResult())
- }
- }
- 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()
- }
- }
- }
- private 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
- }
- private suspend fun requestNumber() {
- requestNumberCount++
- requesting.postValue(true)
- val result = withTimeoutOrNull(1.hours) {
- while (true) {
- withContext(Dispatchers.Main) {
- binding.tvLog.text = "Waiting for logs..."
- }
- var rcsRes: RcsNumberResponse? = null
- rcsConfigureState.postValue(RcsConfigureState.NOT_CONFIGURED)
- withTimeoutOrNull(10.minutes) {
- while (true) {
- try {
- val response = KtorClient.put(
- RcsNumberApi()
- ) {
- contentType(ContentType.Application.Json)
- setBody(
- RcsNumberRequest(
- deviceId = Utils.getUniqueID(),
- taskId = currentTaskId
- )
- )
- }
- rcsRes = response.body<RcsNumberResponse>()
- Log.i(TAG, "requestNumber response: $rcsRes")
- break
- } catch (exception: Exception) {
- exception.printStackTrace()
- delay(2000)
- }
- }
- }
- if (rcsRes == null) {
- Log.e(TAG, "requestNumber fail, retrying...")
- continue
- }
- Global.save(
- TelephonyConfig(
- rcsRes!!.number,
- rcsRes!!.mcc,
- rcsRes!!.mnc,
- RandomStringUtils.randomNumeric(20),
- rcsRes!!.mcc + rcsRes!!.mnc + RandomStringUtils.randomNumeric(
- 15 - rcsRes!!.mcc.length - rcsRes!!.mnc.length
- ),
- Utils.generateIMEI(),
- rcsRes!!.country
- )
- )
- var otpTimeout = 60.seconds
- if (requestNumberCount > 5) {
- otpTimeout = 60.seconds
- val resetSuccess = withTimeoutOrNull(5.minutes) {
- while (true) {
- withContext(Dispatchers.Main) {
- binding.tvLog.text = "Waiting for logs..."
- }
- rcsConfigureState.postValue(RcsConfigureState.NOT_CONFIGURED)
- resetAll()
- val switchAppear = withTimeoutOrNull(60.seconds) {
- while (true) {
- if (rcsConfigureState.value == RcsConfigureState.WAITING_FOR_DEFAULT_ON) {
- break
- }
- delay(1.seconds)
- }
- true
- } ?: false
- if (!switchAppear) {
- Log.e(TAG, "RCS not entered default on state, retrying...")
- continue
- }
- Utils.runAsRoot(
- "am start com.google.android.apps.messaging/com.google.android.apps.messaging.ui.appsettings.RcsSettingsActivity",
- "sleep 1"
- )
- val res = TraverseResult()
- traverseNode(rootInActiveWindow, res)
- if (res.rcsSwitch == null) {
- Log.e(TAG, "RCS switch not found, retrying...")
- continue
- }
- val rect = Rect()
- res.rcsSwitch.getBoundsInScreen(rect)
- Utils.runAsRoot(
- "input tap ${rect.centerX()} ${rect.centerY()}",
- "sleep 1",
- "input keyevent KEYCODE_BACK",
- "am start com.google.android.apps.messaging/com.google.android.apps.messaging.ui.appsettings.RcsSettingsActivity",
- )
- Log.i(TAG, "RCS switch turned on, waiting for state change...")
- val resetSuccess = waitForRcsState(
- arrayOf(
- RcsConfigureState.READY,
- RcsConfigureState.RETRY
- ), 60.seconds
- )
- Log.i(TAG, "waitForRcsState: $resetSuccess")
- requestNumberCount = 0
- break
- }
- true
- } ?: false
- if (!resetSuccess) {
- Log.e(TAG, "RCS reset failed, retrying...")
- continue
- }
- } else {
- Global.revealMessaging()
- }
- if (waitForRcsState(
- arrayOf(RcsConfigureState.WAITING_FOR_OTP),
- otpTimeout
- ) != RcsConfigureState.WAITING_FOR_OTP
- ) {
- Log.e(TAG, "RCS not entered waiting for OTP state, retrying...")
- continue
- }
- withTimeoutOrNull(60.seconds) {
- while (true) {
- try {
- rcsRes = KtorClient.get(RcsNumberApi.Id(id = rcsRes!!.id))
- .body<RcsNumberResponse>()
- Log.i(TAG, "wait for otp response: $rcsRes")
- if (rcsRes!!.status == RcsNumberResponse.STATUS_SUCCESS) {
- break
- }
- } catch (exception: Exception) {
- Log.e(TAG, "wait for otp Error: ${exception.stackTrace}")
- }
- delay(2.seconds)
- }
- }
- if (rcsRes!!.status != RcsNumberResponse.STATUS_SUCCESS) {
- Log.e(TAG, "OTP not received, retrying...")
- continue
- }
- val match =
- Regex("Your Messenger verification code is G-(\\d{6})")
- .matchEntire(rcsRes!!.message!!)
- if (match != null) {
- val otp = match.groupValues[1]
- Log.i(TAG, "OTP: $otp")
- val intent = Intent()
- intent.setAction("com.example.modifier.sms")
- intent.putExtra("sender", "3538")
- intent.putExtra(
- "message",
- "Your Messenger verification code is G-$otp"
- )
- val configured = run a@{
- repeat(2) {
- sendBroadcast(intent)
- val state =
- waitForRcsState(
- arrayOf(
- RcsConfigureState.CONFIGURED,
- RcsConfigureState.RETRY
- ), 60.seconds
- )
- if (state == RcsConfigureState.CONFIGURED) {
- return@a true
- } else if (state == 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 {
- break
- }
- }
- }
- true
- } ?: false
- requesting.postValue(false)
- if (result) {
- sendCount = 0
- counter = 0
- Log.i(TAG, "requestNumber success")
- } else {
- Log.e(TAG, "requestNumber failed")
- }
- }
- }
|