x1ongzhu 1 an în urmă
părinte
comite
4fa78d12c7

+ 1 - 0
app/src/main/java/com/example/modifier/http/KtorClient.kt

@@ -60,6 +60,7 @@ fun ktorClient(baseUrl: String) = HttpClient(OkHttp) {
                 }
             }
         }
+        delayMillis { 1000 }
     }
     install(HttpTimeout) {
         requestTimeoutMillis = 30 * 1000

+ 16 - 6
app/src/main/java/com/example/modifier/repo/AppStateRepository.kt

@@ -1,6 +1,7 @@
 package com.example.modifier.repo
 
 import android.content.Context
+import android.util.Log
 import androidx.datastore.preferences.core.booleanPreferencesKey
 import androidx.datastore.preferences.core.edit
 import androidx.datastore.preferences.core.intPreferencesKey
@@ -13,8 +14,10 @@ import com.example.modifier.data.AppState
 import com.example.modifier.enums.RequestNumberState
 import kotlinx.coroutines.CoroutineScope
 import kotlinx.coroutines.MainScope
+import kotlinx.coroutines.flow.MutableStateFlow
 import kotlinx.coroutines.flow.combine
 import kotlinx.coroutines.flow.stateIn
+import kotlinx.coroutines.flow.update
 import kotlinx.coroutines.launch
 import kotlin.coroutines.coroutineContext
 
@@ -31,12 +34,15 @@ class AppStateRepository(
         val REQUESTED_NUM = intPreferencesKey("requested_num")
     }
 
-    private val appRuntimeFlags = MutableLiveData(AppRuntimeFlags())
+    private val appRuntimeFlags = MutableStateFlow(AppRuntimeFlags())
 
     private val appStateFlow =
-        context.appStateDataStore.data.combine(appRuntimeFlags.asFlow()) { preferences, runtimeFlags ->
+        context.appStateDataStore.data.combine(appRuntimeFlags) { preferences, runtimeFlags ->
             val sPrefs =
                 context.getSharedPreferences(BuildConfig.APPLICATION_ID, Context.MODE_PRIVATE)
+            val busy =
+                runtimeFlags.running || runtimeFlags.requesting || runtimeFlags.preparing || runtimeFlags.checkingConnection
+            Log.i("AppStateRepository.appStateFlow", "running: ${runtimeFlags.running}, \nrequesting: ${runtimeFlags.requesting}, \npreparing: ${runtimeFlags.preparing}, \ncheckingConnection: ${runtimeFlags.checkingConnection}, \nbusy: $busy")
             AppState(
                 send = preferences[PreferencesKeys.SEND] ?: false,
                 executedNum = preferences[PreferencesKeys.EXECUTED_NUM] ?: 0,
@@ -113,9 +119,13 @@ class AppStateRepository(
         suspended: Boolean? = null,
         requestNumberState: RequestNumberState? = null
     ) {
-        val value = appRuntimeFlags.value ?: AppRuntimeFlags()
-        appRuntimeFlags.postValue(
-            value.copy(
+        Log.i(
+            "AppStateRepository.updateRuntimeFlags",
+            "running: $running, \nrequesting: $requesting, \npreparing: $preparing, \ncheckingConnection: $checkingConnection, \nsuspended: $suspended, \nrequestNumberState: $requestNumberState"
+        )
+        val value = appRuntimeFlags.value
+        appRuntimeFlags.update {
+            it.copy(
                 running = running ?: value.running,
                 requesting = requesting ?: value.requesting,
                 preparing = preparing ?: value.preparing,
@@ -123,6 +133,6 @@ class AppStateRepository(
                 suspended = suspended ?: value.suspended,
                 requestNumberState = requestNumberState ?: value.requestNumberState
             )
-        )
+        }
     }
 }

+ 1 - 2
app/src/main/java/com/example/modifier/repo/GoogleMessageStateRepository.kt

@@ -64,12 +64,11 @@ class GoogleMessageStateRepository(context: Context) {
                                 val log = groups["log"]?.value
                                     ?.replace(Regex("\\[\\w+-\\w+-\\w+-\\w+-\\w+]"), "")
                                     ?.replace(Regex("\\[CONTEXT.*]"), "")
-                                    ?.replace("transitionTo: destState=", "")
                                     ?.trim()
 
                                 if (time != null && log != null) {
                                     if (log.contains("destState=")) {
-                                        logsCache.add("$time: $log")
+                                        logsCache.add("$time\n${log.replace("transitionTo: destState=", "")}")
                                         logs.postValue(logsCache.joinToString("\n"))
                                         delay(100)
                                         logs.postValue(logsCache.joinToString("\n"))

+ 28 - 25
app/src/main/java/com/example/modifier/service/SocketClient.kt

@@ -87,15 +87,9 @@ class SocketClient(
                     val taskAction = Json.decodeFromString<TaskAction>(json.toString())
                     CoroutineScope(Dispatchers.IO).launch {
                         taskRunner.runTask(taskAction, onSuccess = { res ->
-                            emitEvent("callback", res)
+                            socketCallback(taskAction.id, res)
                         }, onError = { error ->
-                            emitEvent(
-                                "callback", SocketCallback<String>(
-                                    id = taskAction.id,
-                                    status = -1,
-                                    error = error.message
-                                )
-                            )
+                            socketCallback(taskAction.id, -1, error.message)
                         })
                     }
                 } else if ("installApk" == action) {
@@ -103,20 +97,9 @@ class SocketClient(
 
                     CoroutineScope(Dispatchers.IO).launch {
                         taskRunner.installApk(installApkAction, onSuccess = {
-                            emitEvent(
-                                "callback", SocketCallback<String>(
-                                    id = installApkAction.id,
-                                    status = 0,
-                                )
-                            )
+                            socketCallback(installApkAction.id, 0)
                         }, onError = { error ->
-                            emitEvent(
-                                "callback", SocketCallback<String>(
-                                    id = installApkAction.id,
-                                    status = -1,
-                                    error = error.message
-                                )
-                            )
+                            socketCallback(installApkAction.id, -1, error.message)
                         })
                     }
                 }
@@ -149,17 +132,37 @@ class SocketClient(
         }
     }
 
-    fun emitEvent(event: String, data: TaskExecutionResult) {
+    private fun socketCallback(id: String, data: TaskExecutionResult) {
         try {
-            mSocket.emit(event, JSONObject(Json.encodeToString(data)))
+            mSocket.emit(
+                "callback", JSONObject(
+                    Json.encodeToString(
+                        SocketCallback(
+                            id = id,
+                            status = 0,
+                            data = data
+                        )
+                    )
+                )
+            )
         } catch (e: Exception) {
             Log.e(tag, "emitEvent error", e)
         }
     }
 
-    fun <T> emitEvent(event: String, data: SocketCallback<T>) {
+    private fun socketCallback(id: String, status: Int, error: String? = null) {
         try {
-            mSocket.emit(event, JSONObject(Json.encodeToString(data)))
+            mSocket.emit(
+                "callback", JSONObject(
+                    Json.encodeToString(
+                        SocketCallback<String>(
+                            id = id,
+                            status = status,
+                            error = error
+                        )
+                    )
+                )
+            )
         } catch (e: Exception) {
             Log.e(tag, "emitEvent error", e)
         }

+ 23 - 40
app/src/main/java/com/example/modifier/service/TaskRunner.kt

@@ -81,6 +81,7 @@ import org.json.JSONObject
 import java.io.File
 import java.time.LocalDateTime
 import java.time.temporal.ChronoUnit
+import kotlin.time.Duration.Companion.days
 import kotlin.time.Duration.Companion.hours
 import kotlin.time.Duration.Companion.minutes
 import kotlin.time.Duration.Companion.seconds
@@ -194,7 +195,7 @@ class TaskRunner(
                 appStateRepository.updateRuntimeFlags(checkingConnection = false)
             }
 
-            appStateRepository.updateRuntimeFlags(running = true)
+            appStateRepository.updateRuntimeFlags(running = true, checkingConnection = false)
             val success = ArrayList<Int>()
             val fail = ArrayList<Int>()
             for (i in 0 until taskAction.data.tasks.size) {
@@ -432,7 +433,7 @@ class TaskRunner(
                     if (requestMode == 2 && !noBackup) {
                         val backup = backupRepository.findBackupForRestore(
                             spoofedSimInfo.value.number,
-                            System.currentTimeMillis() - 2 * 24 * 60 * 60 * 1000
+                            System.currentTimeMillis() - 2.days.inWholeMilliseconds
                         )
                         if (backup != null) {
                             if (backupRepository.restore(backup)) {
@@ -522,16 +523,10 @@ class TaskRunner(
                             needRest = true
                         }
                         if (RcsConfigureState.REPLAY_REQUEST == googleMessageStateRepository.rcsConfigureState.value) {
-                            Log.e(
-                                TAG,
-                                "REPLAY_REQUEST detected, may reset after 3 retry ($retry)"
-                            )
+                            Log.e(TAG, "REPLAY_REQUEST detected, may reset after 3 retry ($retry)")
                             retry++
                         }
-                        Log.e(
-                            TAG,
-                            "RCS not entered waiting for OTP state, retrying..."
-                        )
+                        Log.e(TAG, "RCS not entered waiting for OTP state, retrying...")
                         continue
                     }
 
@@ -567,10 +562,7 @@ class TaskRunner(
                                     break
                                 }
                             } catch (exception: Exception) {
-                                Log.e(
-                                    TAG,
-                                    "wait for otp Error: ${exception.stackTrace}"
-                                )
+                                Log.e(TAG, "wait for otp Error: ${exception.stackTrace}")
                             }
                             delay(2.seconds)
                         }
@@ -615,10 +607,7 @@ class TaskRunner(
                                     }
 
                                     else -> {
-                                        Log.e(
-                                            TAG,
-                                            "verifyOtp fail, retrying..."
-                                        )
+                                        Log.e(TAG, "verifyOtp fail, retrying...")
                                     }
                                 }
                             }
@@ -701,35 +690,30 @@ class TaskRunner(
     }
 
     suspend fun checkRcsAvailability(): Boolean {
-        appStateRepository.updateRuntimeFlags(checkingConnection = true)
         val availability = run checkAvailability@{
             val rcsConnected = checkRcsConnectivity()
             if (!rcsConnected) {
                 return@checkAvailability false
             }
 
-            var config: SysConfigResponse
             val checkRcsAvailabilityNumbers = mutableListOf<String>()
-            withTimeoutOrNull(60.seconds) {
-                try {
-                    config = ktorClient(appPreferences.value.server).get(
-                        SysConfigApi.Id(
-                            SysConfigApi(),
-                            "check_availability_numbers"
-                        )
-                    )
-                        .body<SysConfigResponse>()
-                    Log.i(TAG, "sysConfig response: $config")
-                    checkRcsAvailabilityNumbers.addAll(
-                        config.value.split(",").map { it.trim() })
-
-                } catch (exception: Exception) {
-                    Log.e(
-                        TAG,
-                        "sysConfig Error: ${exception.message}",
-                        exception
+            try {
+                val config = ktorClient(appPreferences.value.server).get(
+                    SysConfigApi.Id(
+                        SysConfigApi(),
+                        "check_availability_numbers"
                     )
-                }
+                )
+                    .body<SysConfigResponse>()
+                Log.i(TAG, "sysConfig response: $config")
+                checkRcsAvailabilityNumbers.addAll(
+                    config.value.split(",").map { it.trim() })
+            } catch (exception: Exception) {
+                Log.e(
+                    TAG,
+                    "sysConfig Error: ${exception.message}",
+                    exception
+                )
             }
 
             if (checkRcsAvailabilityNumbers.isEmpty()) {
@@ -762,7 +746,6 @@ class TaskRunner(
             }
             false
         }
-        appStateRepository.updateRuntimeFlags(checkingConnection = false)
         return availability
     }
 

+ 19 - 3
app/src/test/java/com/example/modifier/ExampleUnitTest.kt

@@ -1,9 +1,14 @@
 package com.example.asdfasdfawf
 
+import android.util.Log
 import com.example.modifier.Utils
+import com.example.modifier.model.SocketCallback
+import com.example.modifier.model.TaskExecutionResult
+import com.example.modifier.serializer.Json
 import com.example.modifier.utils.genICCID
 import com.example.modifier.utils.genIMEI
 import com.example.modifier.utils.genIMSI
+import com.google.android.gms.tasks.Task
 import kotlinx.coroutines.CoroutineScope
 import kotlinx.coroutines.Dispatchers
 import kotlinx.coroutines.coroutineScope
@@ -11,6 +16,8 @@ import kotlinx.coroutines.delay
 import kotlinx.coroutines.launch
 import kotlinx.coroutines.runBlocking
 import kotlinx.coroutines.withTimeout
+import kotlinx.serialization.encodeToString
+import org.json.JSONObject
 import org.junit.Test
 
 import org.junit.Assert.*
@@ -27,8 +34,17 @@ import java.time.format.DateTimeFormatter
 class ExampleUnitTest {
     @Test
     fun test1() {
-        println(genIMEI())
-        println(genICCID("240", "1"))
-        println(genIMSI("310240"))
+        println(
+            Json.encodeToString(
+                SocketCallback<String>(
+                    id = "1",
+                    status = 1
+                )
+            )
+        )
+    }
+
+    private fun socketCallback(data: TaskExecutionResult) {
+
     }
 }