优化:发送通道webhook支持HTTP基本认证 【格式:http://username:password@domain.com/uri】 #175

优化:发送通道`企业微信应用`获取access_token失败时记录错误日志
优化:发送通道`短信`发送权限未授权/仅当无网络启用时记录错误日志
This commit is contained in:
pppscn 2022-06-30 11:02:29 +08:00
parent 3d2406a44b
commit f142f8d958
14 changed files with 115 additions and 249 deletions

View File

@ -7,8 +7,10 @@ import java.security.cert.X509Certificate
import java.util.* import java.util.*
import javax.net.ssl.* import javax.net.ssl.*
@Suppress("unused")
@SuppressLint("ALL") @SuppressLint("ALL")
object CertUtils { object CertUtils {
//获取这个SSLSocketFactory //获取这个SSLSocketFactory
val sSLSocketFactory: SSLSocketFactory val sSLSocketFactory: SSLSocketFactory
get() = try { get() = try {

View File

@ -84,9 +84,8 @@ class BarkUtils {
.execute(object : SimpleCallBack<String>() { .execute(object : SimpleCallBack<String>() {
override fun onError(e: ApiException) { override fun onError(e: ApiException) {
SendUtils.updateLogs(logId, 0, e.displayMessage)
Log.e(TAG, e.detailMessage) Log.e(TAG, e.detailMessage)
//XToastUtils.error(e.displayMessage) SendUtils.updateLogs(logId, 0, e.displayMessage)
} }
override fun onSuccess(response: String) { override fun onSuccess(response: String) {
@ -95,10 +94,8 @@ class BarkUtils {
val resp = Gson().fromJson(response, BarkResult::class.java) val resp = Gson().fromJson(response, BarkResult::class.java)
if (resp.code == 200L) { if (resp.code == 200L) {
SendUtils.updateLogs(logId, 2, response) SendUtils.updateLogs(logId, 2, response)
//XToastUtils.success(ResUtils.getString(R.string.request_succeeded))
} else { } else {
SendUtils.updateLogs(logId, 0, response) SendUtils.updateLogs(logId, 0, response)
//XToastUtils.error(ResUtils.getString(R.string.request_failed) + response)
} }
} }

View File

@ -95,9 +95,8 @@ class DingtalkUtils private constructor() {
.execute(object : SimpleCallBack<String>() { .execute(object : SimpleCallBack<String>() {
override fun onError(e: ApiException) { override fun onError(e: ApiException) {
SendUtils.updateLogs(logId, 0, e.displayMessage)
Log.e(TAG, e.detailMessage) Log.e(TAG, e.detailMessage)
//XToastUtils.error(e.displayMessage) SendUtils.updateLogs(logId, 0, e.displayMessage)
} }
override fun onSuccess(response: String) { override fun onSuccess(response: String) {
@ -106,10 +105,8 @@ class DingtalkUtils private constructor() {
val resp = Gson().fromJson(response, DingtalkResult::class.java) val resp = Gson().fromJson(response, DingtalkResult::class.java)
if (resp.errcode == 0L) { if (resp.errcode == 0L) {
SendUtils.updateLogs(logId, 2, response) SendUtils.updateLogs(logId, 2, response)
//XToastUtils.success(ResUtils.getString(R.string.request_succeeded))
} else { } else {
SendUtils.updateLogs(logId, 0, response) SendUtils.updateLogs(logId, 0, response)
//XToastUtils.error(ResUtils.getString(R.string.request_failed) + response)
} }
} }

View File

@ -141,14 +141,12 @@ class EmailUtils {
MailSender.getInstance().sendMail(mail, object : MailSender.OnMailSendListener { MailSender.getInstance().sendMail(mail, object : MailSender.OnMailSendListener {
override fun onError(e: Throwable) { override fun onError(e: Throwable) {
SendUtils.updateLogs(logId, 0, e.message.toString())
Log.e("MailSender", e.message.toString()) Log.e("MailSender", e.message.toString())
//XToastUtils.error(ResUtils.getString(R.string.request_failed) + e.message.toString()) SendUtils.updateLogs(logId, 0, e.message.toString())
} }
override fun onSuccess() { override fun onSuccess() {
SendUtils.updateLogs(logId, 2, ResUtils.getString(R.string.request_succeeded)) SendUtils.updateLogs(logId, 2, ResUtils.getString(R.string.request_succeeded))
//XToastUtils.success(ResUtils.getString(R.string.request_succeeded))
} }
}) })

View File

@ -143,9 +143,8 @@ class FeishuUtils private constructor() {
.execute(object : SimpleCallBack<String>() { .execute(object : SimpleCallBack<String>() {
override fun onError(e: ApiException) { override fun onError(e: ApiException) {
SendUtils.updateLogs(logId, 0, e.displayMessage)
Log.e(TAG, e.detailMessage) Log.e(TAG, e.detailMessage)
//XToastUtils.error(e.displayMessage) SendUtils.updateLogs(logId, 0, e.displayMessage)
} }
override fun onSuccess(response: String) { override fun onSuccess(response: String) {
@ -154,10 +153,8 @@ class FeishuUtils private constructor() {
val resp = Gson().fromJson(response, FeishuResult::class.java) val resp = Gson().fromJson(response, FeishuResult::class.java)
if (resp.code == 0L) { if (resp.code == 0L) {
SendUtils.updateLogs(logId, 2, response) SendUtils.updateLogs(logId, 2, response)
//XToastUtils.success(ResUtils.getString(R.string.request_succeeded))
} else { } else {
SendUtils.updateLogs(logId, 0, response) SendUtils.updateLogs(logId, 0, response)
//XToastUtils.error(ResUtils.getString(R.string.request_failed) + response)
} }
} }

View File

@ -62,9 +62,8 @@ class GotifyUtils {
.execute(object : SimpleCallBack<String>() { .execute(object : SimpleCallBack<String>() {
override fun onError(e: ApiException) { override fun onError(e: ApiException) {
SendUtils.updateLogs(logId, 0, e.displayMessage)
Log.e(TAG, e.detailMessage) Log.e(TAG, e.detailMessage)
//XToastUtils.error(e.displayMessage) SendUtils.updateLogs(logId, 0, e.displayMessage)
} }
override fun onSuccess(response: String) { override fun onSuccess(response: String) {
@ -73,10 +72,8 @@ class GotifyUtils {
val resp = Gson().fromJson(response, GotifyResult::class.java) val resp = Gson().fromJson(response, GotifyResult::class.java)
if (resp?.id != null) { if (resp?.id != null) {
SendUtils.updateLogs(logId, 2, response) SendUtils.updateLogs(logId, 2, response)
//XToastUtils.success(ResUtils.getString(R.string.request_succeeded))
} else { } else {
SendUtils.updateLogs(logId, 0, response) SendUtils.updateLogs(logId, 0, response)
//XToastUtils.error(ResUtils.getString(R.string.request_failed) + response)
} }
} }

View File

@ -79,9 +79,8 @@ class PushplusUtils private constructor() {
.execute(object : SimpleCallBack<String>() { .execute(object : SimpleCallBack<String>() {
override fun onError(e: ApiException) { override fun onError(e: ApiException) {
SendUtils.updateLogs(logId, 0, e.displayMessage)
Log.e(TAG, e.detailMessage) Log.e(TAG, e.detailMessage)
//XToastUtils.error(e.displayMessage) SendUtils.updateLogs(logId, 0, e.displayMessage)
} }
override fun onSuccess(response: String) { override fun onSuccess(response: String) {
@ -90,10 +89,8 @@ class PushplusUtils private constructor() {
val resp = Gson().fromJson(response, PushplusResult::class.java) val resp = Gson().fromJson(response, PushplusResult::class.java)
if (resp.code == 200L) { if (resp.code == 200L) {
SendUtils.updateLogs(logId, 2, response) SendUtils.updateLogs(logId, 2, response)
//XToastUtils.success(ResUtils.getString(R.string.request_succeeded))
} else { } else {
SendUtils.updateLogs(logId, 0, response) SendUtils.updateLogs(logId, 0, response)
//XToastUtils.error(ResUtils.getString(R.string.request_failed) + response)
} }
} }

View File

@ -1,88 +0,0 @@
package com.idormy.sms.forwarder.utils.sender
import android.util.Log
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
import java.io.IOException
import java.io.InterruptedIOException
class RetryInterceptor internal constructor(builder: Builder) : Interceptor {
//重试的间隔
private val retryInterval: Long
//更新记录ID
private val logId: Long
//最大重试次数
private val executionCount: Int
@Throws(IOException::class)
override fun intercept(chain: Interceptor.Chain): Response {
var retryTimes = 0
val request = chain.request()
var response: Response
do {
if (retryTimes > 0 && retryInterval > 0) {
val delayTime = retryTimes * retryInterval
try {
Log.w(TAG, "$retryTimes 次重试,休眠 $delayTime")
Thread.sleep(delayTime * 1000)
} catch (e: InterruptedException) {
Thread.currentThread().interrupt()
throw InterruptedIOException(e.message)
}
}
response = doRequest(chain, request, retryTimes)!!
retryTimes++
} while ((!response.isSuccessful) && retryTimes <= executionCount)
return response
}
private fun doRequest(chain: Interceptor.Chain, request: Request, retryTimes: Int): Response? {
var response: Response? = null
try {
response = chain.proceed(request)
} catch (e: Exception) {
val resp = if (retryTimes > 0) "" + retryTimes + "次重试:" + e.message else e.message!!
//LogUtils.updateLog(logId, 1, resp);
Log.w(TAG, resp)
}
return response
}
class Builder {
var executionCount = 3
var retryInterval: Long = 1000
var logId: Long = 0
fun executionCount(executionCount: Int): Builder {
this.executionCount = executionCount
return this
}
fun retryInterval(retryInterval: Long): Builder {
this.retryInterval = retryInterval
return this
}
fun logId(logId: Long): Builder {
this.logId = logId
return this
}
fun build(): RetryInterceptor {
return RetryInterceptor(this)
}
}
companion object {
const val TAG = "RetryInterceptor"
}
init {
executionCount = builder.executionCount
retryInterval = builder.retryInterval
logId = builder.logId
}
}

View File

@ -57,9 +57,8 @@ class ServerchanUtils {
.execute(object : SimpleCallBack<String>() { .execute(object : SimpleCallBack<String>() {
override fun onError(e: ApiException) { override fun onError(e: ApiException) {
SendUtils.updateLogs(logId, 0, e.displayMessage)
Log.e(TAG, e.detailMessage) Log.e(TAG, e.detailMessage)
//XToastUtils.error(e.displayMessage) SendUtils.updateLogs(logId, 0, e.displayMessage)
} }
override fun onSuccess(response: String) { override fun onSuccess(response: String) {
@ -68,10 +67,8 @@ class ServerchanUtils {
val resp = Gson().fromJson(response, ServerchanResult::class.java) val resp = Gson().fromJson(response, ServerchanResult::class.java)
if (resp?.code == 0L) { if (resp?.code == 0L) {
SendUtils.updateLogs(logId, 2, response) SendUtils.updateLogs(logId, 2, response)
//XToastUtils.success(ResUtils.getString(R.string.request_succeeded))
} else { } else {
SendUtils.updateLogs(logId, 0, response) SendUtils.updateLogs(logId, 0, response)
//XToastUtils.error(ResUtils.getString(R.string.request_failed) + response)
} }
} }

View File

@ -30,6 +30,12 @@ class SmsUtils {
) { ) {
//仅当无网络时启用 && 判断是否真实有网络 //仅当无网络时启用 && 判断是否真实有网络
if (setting.onlyNoNetwork == true && NetworkUtils.isHaveInternet() && NetworkUtils.isAvailableByPing()) { if (setting.onlyNoNetwork == true && NetworkUtils.isHaveInternet() && NetworkUtils.isAvailableByPing()) {
SendUtils.updateLogs(logId, 0, ResUtils.getString(R.string.OnlyNoNetwork))
return
}
if (ActivityCompat.checkSelfPermission(XUtil.getContext(), Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED) {
SendUtils.updateLogs(logId, 0, ResUtils.getString(R.string.no_sms_sending_permission))
return return
} }
@ -50,18 +56,11 @@ class SmsUtils {
//TODO取不到卡槽信息时采用默认卡槽发送 //TODO取不到卡槽信息时采用默认卡槽发送
val mSubscriptionId: Int = App.SimInfoList[simSlotIndex]?.mSubscriptionId ?: -1 val mSubscriptionId: Int = App.SimInfoList[simSlotIndex]?.mSubscriptionId ?: -1
if (ActivityCompat.checkSelfPermission(XUtil.getContext(), Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED) {
//XToastUtils.error(ResUtils.getString(R.string.no_sms_sending_permission))
return
}
val res: String? = PhoneUtils.sendSms(mSubscriptionId, setting.mobiles, content) val res: String? = PhoneUtils.sendSms(mSubscriptionId, setting.mobiles, content)
if (res == null) { if (res == null) {
SendUtils.updateLogs(logId, 2, ResUtils.getString(R.string.request_succeeded)) SendUtils.updateLogs(logId, 2, ResUtils.getString(R.string.request_succeeded))
//XToastUtils.success(ResUtils.getString(R.string.request_succeeded))
} else { } else {
SendUtils.updateLogs(logId, 0, res) SendUtils.updateLogs(logId, 0, res)
//XToastUtils.error(ResUtils.getString(R.string.request_failed) + res)
} }
} }

View File

@ -110,9 +110,8 @@ class TelegramUtils private constructor() {
.execute(object : SimpleCallBack<String>() { .execute(object : SimpleCallBack<String>() {
override fun onError(e: ApiException) { override fun onError(e: ApiException) {
SendUtils.updateLogs(logId, 0, e.displayMessage)
Log.e(TAG, e.detailMessage) Log.e(TAG, e.detailMessage)
//XToastUtils.error(e.displayMessage) SendUtils.updateLogs(logId, 0, e.displayMessage)
} }
override fun onSuccess(response: String) { override fun onSuccess(response: String) {
@ -121,10 +120,8 @@ class TelegramUtils private constructor() {
val resp = Gson().fromJson(response, TelegramResult::class.java) val resp = Gson().fromJson(response, TelegramResult::class.java)
if (resp.ok == true) { if (resp.ok == true) {
SendUtils.updateLogs(logId, 2, response) SendUtils.updateLogs(logId, 2, response)
//XToastUtils.success(ResUtils.getString(R.string.request_succeeded))
} else { } else {
SendUtils.updateLogs(logId, 0, response) SendUtils.updateLogs(logId, 0, response)
//XToastUtils.error(ResUtils.getString(R.string.request_failed) + response)
} }
} }

View File

@ -1,7 +1,6 @@
package com.idormy.sms.forwarder.utils.sender package com.idormy.sms.forwarder.utils.sender
import android.annotation.SuppressLint import android.annotation.SuppressLint
import android.os.Looper
import android.text.TextUtils import android.text.TextUtils
import android.util.Base64 import android.util.Base64
import android.util.Log import android.util.Log
@ -9,17 +8,17 @@ import com.google.gson.Gson
import com.idormy.sms.forwarder.database.entity.Rule import com.idormy.sms.forwarder.database.entity.Rule
import com.idormy.sms.forwarder.entity.MsgInfo import com.idormy.sms.forwarder.entity.MsgInfo
import com.idormy.sms.forwarder.entity.setting.WebhookSetting import com.idormy.sms.forwarder.entity.setting.WebhookSetting
import com.idormy.sms.forwarder.utils.CertUtils
import com.idormy.sms.forwarder.utils.SendUtils import com.idormy.sms.forwarder.utils.SendUtils
import com.idormy.sms.forwarder.utils.SettingUtils import com.idormy.sms.forwarder.utils.SettingUtils
import com.xuexiang.xhttp2.XHttp
import com.xuexiang.xhttp2.cache.model.CacheMode
import com.xuexiang.xhttp2.callback.SimpleCallBack
import com.xuexiang.xhttp2.exception.ApiException
import com.xuexiang.xutil.app.AppUtils import com.xuexiang.xutil.app.AppUtils
import okhttp3.*
import java.io.IOException
import java.net.URLEncoder import java.net.URLEncoder
import java.nio.charset.StandardCharsets import java.nio.charset.StandardCharsets
import java.text.SimpleDateFormat import java.text.SimpleDateFormat
import java.util.* import java.util.*
import java.util.concurrent.TimeUnit
import javax.crypto.Mac import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec import javax.crypto.spec.SecretKeySpec
@ -42,8 +41,8 @@ class WebhookUtils {
msgInfo.getContentForSend(SettingUtils.smsTemplate.toString()) msgInfo.getContentForSend(SettingUtils.smsTemplate.toString())
} }
var webServer: String = setting.webServer //推送地址 var requestUrl: String = setting.webServer //推送地址
Log.i(TAG, "requestUrl:$webServer") Log.i(TAG, "requestUrl:$requestUrl")
val timestamp = System.currentTimeMillis() val timestamp = System.currentTimeMillis()
val orgContent: String = msgInfo.content val orgContent: String = msgInfo.content
@ -62,16 +61,25 @@ class WebhookUtils {
} }
var webParams = setting.webParams?.trim() var webParams = setting.webParams?.trim()
val requestBuilder: Request.Builder
if (setting.method == "GET" && TextUtils.isEmpty(webParams)) { //支持HTTP基本认证(Basic Authentication)
val regex = "^(https?://)([^:]+):([^@]+)@(.+)"
val matches = Regex(regex, RegexOption.IGNORE_CASE).findAll(requestUrl).toList().flatMap(MatchResult::groupValues)
Log.i(TAG, "matches = $matches")
if (matches.isNotEmpty()) {
requestUrl = matches[1] + matches[4]
Log.i(TAG, "requestUrl:$requestUrl")
}
val request = if (setting.method == "GET" && TextUtils.isEmpty(webParams)) {
setting.webServer += (if (setting.webServer.contains("?")) "&" else "?") + "from=" + URLEncoder.encode(from, "UTF-8") setting.webServer += (if (setting.webServer.contains("?")) "&" else "?") + "from=" + URLEncoder.encode(from, "UTF-8")
webServer += "&content=" + URLEncoder.encode(content, "UTF-8") requestUrl += "&content=" + URLEncoder.encode(content, "UTF-8")
if (!TextUtils.isEmpty(setting.secret)) { if (!TextUtils.isEmpty(sign)) {
webServer += "&timestamp=$timestamp" requestUrl += "&timestamp=$timestamp"
webServer += "&sign=$sign" requestUrl += "&sign=$sign"
} }
Log.d(TAG, "method = GET, Url = $webServer") Log.d(TAG, "method = GET, Url = $requestUrl")
requestBuilder = Request.Builder().url(webServer).get() XHttp.get(requestUrl).keepJson(true)
} else if (setting.method == "GET" && !TextUtils.isEmpty(webParams)) { } else if (setting.method == "GET" && !TextUtils.isEmpty(webParams)) {
webParams = webParams.toString().replace("[from]", URLEncoder.encode(from, "UTF-8")) webParams = webParams.toString().replace("[from]", URLEncoder.encode(from, "UTF-8"))
.replace("[content]", URLEncoder.encode(content, "UTF-8")) .replace("[content]", URLEncoder.encode(content, "UTF-8"))
@ -87,110 +95,83 @@ class WebhookUtils {
webParams = webParams.replace("[timestamp]", timestamp.toString()) webParams = webParams.replace("[timestamp]", timestamp.toString())
.replace("[sign]", URLEncoder.encode(sign, "UTF-8")) .replace("[sign]", URLEncoder.encode(sign, "UTF-8"))
} }
webServer += (if (webServer.contains("?")) "&" else "?") + webParams requestUrl += if (webParams.startsWith("/")) {
Log.d(TAG, "method = GET, Url = $webServer") webParams
requestBuilder = Request.Builder().url(webServer).get()
} else if (webParams != null && !TextUtils.isEmpty(webParams)) {
val bodyMsg: String
var contentType = "application/x-www-form-urlencoded"
if (webParams.startsWith("{")) {
contentType = "application/json;charset=utf-8"
bodyMsg = webParams.replace("[from]", from)
.replace("[content]", escapeJson(content))
.replace("[msg]", escapeJson(content))
.replace("[org_content]", escapeJson(orgContent))
.replace("[device_mark]", escapeJson(deviceMark))
.replace("[app_version]", appVersion)
.replace("[title]", escapeJson(simInfo))
.replace("[card_slot]", escapeJson(simInfo))
.replace("[receive_time]", receiveTime)
.replace("[timestamp]", timestamp.toString())
.replace("[sign]", sign)
} else { } else {
bodyMsg = webParams.replace("[from]", URLEncoder.encode(from, "UTF-8")) (if (requestUrl.contains("?")) "&" else "?") + webParams
.replace("[content]", URLEncoder.encode(content, "UTF-8"))
.replace("[msg]", URLEncoder.encode(content, "UTF-8"))
.replace("[org_content]", URLEncoder.encode(orgContent, "UTF-8"))
.replace("[device_mark]", URLEncoder.encode(deviceMark, "UTF-8"))
.replace("[app_version]", URLEncoder.encode(appVersion, "UTF-8"))
.replace("[title]", URLEncoder.encode(simInfo, "UTF-8"))
.replace("[card_slot]", URLEncoder.encode(simInfo, "UTF-8"))
.replace("[receive_time]", URLEncoder.encode(receiveTime, "UTF-8"))
.replace("[timestamp]", URLEncoder.encode(timestamp.toString(), "UTF-8"))
.replace("[sign]", URLEncoder.encode(sign, "UTF-8"))
} }
val body = RequestBody.create(MediaType.parse(contentType), bodyMsg) Log.d(TAG, "method = GET, Url = $requestUrl")
requestBuilder = Request.Builder() XHttp.get(requestUrl).keepJson(true)
.url(webServer) } else if (webParams != null && webParams.isNotEmpty() && webParams.startsWith("{")) {
.addHeader("Content-Type", contentType) val bodyMsg = webParams.replace("[from]", from)
.method("POST", body) .replace("[content]", escapeJson(content))
Log.d(TAG, "method = POST webParams, Body = $bodyMsg") .replace("[msg]", escapeJson(content))
.replace("[org_content]", escapeJson(orgContent))
.replace("[device_mark]", escapeJson(deviceMark))
.replace("[app_version]", appVersion)
.replace("[title]", escapeJson(simInfo))
.replace("[card_slot]", escapeJson(simInfo))
.replace("[receive_time]", receiveTime)
.replace("[timestamp]", timestamp.toString())
.replace("[sign]", sign)
Log.d(TAG, "method = POST, Url = $requestUrl, bodyMsg = $bodyMsg")
XHttp.post(requestUrl).keepJson(true).upJson(bodyMsg)
} else { } else {
val builder = MultipartBody.Builder().setType(MultipartBody.FORM) if (webParams == null || webParams.isEmpty()) {
.addFormDataPart("from", from) webParams = "from=[from]&content=[content]&timestamp=[timestamp]"
.addFormDataPart("content", content) if (!TextUtils.isEmpty(sign)) webParams += "&sign=[sign]"
if (!TextUtils.isEmpty(setting.secret)) {
builder.addFormDataPart("timestamp", timestamp.toString())
builder.addFormDataPart("sign", sign)
}
val body: RequestBody = builder.build()
Log.d(TAG, "method = POST, Body = $body")
requestBuilder = Request.Builder().url(webServer).method("POST", body)
}
for ((key, value) in setting.headers?.entries!!) {
requestBuilder.addHeader(key, value)
}
val clientBuilder = OkHttpClient.Builder()
//设置重试拦截器
val retryTimes: Int = SettingUtils.requestRetryTimes
if (retryTimes > 0) {
val delayTime: Long = SettingUtils.requestDelayTime.toLong()
val retryInterceptor: RetryInterceptor = RetryInterceptor.Builder().executionCount(retryTimes).retryInterval(delayTime).logId(0).build()
clientBuilder.addInterceptor(retryInterceptor)
}
//忽略https证书
CertUtils.x509TrustManager?.let { clientBuilder.sslSocketFactory(CertUtils.sSLSocketFactory, it).hostnameVerifier(CertUtils.hostnameVerifier) }
//设置读取超时时间
val client = clientBuilder
.readTimeout(SettingUtils.requestTimeout.toLong(), TimeUnit.SECONDS)
.writeTimeout(SettingUtils.requestTimeout.toLong(), TimeUnit.SECONDS)
.connectTimeout(SettingUtils.requestTimeout.toLong(), TimeUnit.SECONDS)
.build()
client.newCall(requestBuilder.build()).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
//解决在子线程中调用Toast的异常情况处理
if (Looper.myLooper() == null) Looper.prepare()
e.printStackTrace()
SendUtils.updateLogs(logId, 0, e.message.toString())
//XToastUtils.error(ResUtils.getString(R.string.request_failed) + e.message)
Looper.loop()
} }
@Throws(IOException::class) val postRequest = XHttp.post(requestUrl).keepJson(true)
override fun onResponse(call: Call, response: Response) { webParams.split("&").forEach {
val responseStr = response.body().toString() val param = it.split("=")
Log.d(TAG, "Response" + response.code() + "" + responseStr) if (param.size == 2) {
postRequest.params(param[0], param[1].replace("[from]", from)
//返回http状态200即为成功 .replace("[content]", content)
if (200 == response.code()) { .replace("[msg]", content)
if (Looper.myLooper() == null) Looper.prepare() .replace("[org_content]", orgContent)
SendUtils.updateLogs(logId, 2, responseStr) .replace("[device_mark]", deviceMark)
//XToastUtils.success(ResUtils.getString(R.string.request_succeeded)) .replace("[app_version]", appVersion)
Looper.loop() .replace("[title]", simInfo)
} else { .replace("[card_slot]", simInfo)
if (Looper.myLooper() == null) Looper.prepare() .replace("[receive_time]", receiveTime)
SendUtils.updateLogs(logId, 0, responseStr) .replace("[timestamp]", timestamp.toString())
//XToastUtils.error(ResUtils.getString(R.string.request_failed) + response) .replace("[sign]", sign))
Looper.loop()
} }
} }
}) postRequest
}
//添加headers
for ((key, value) in setting.headers?.entries!!) {
request.headers(key, value)
}
//支持HTTP基本认证(Basic Authentication)
if (matches.isNotEmpty()) {
request.addInterceptor(BasicAuthInterceptor(matches[2], matches[3]))
}
request.ignoreHttpsCert() //忽略https证书
.timeOut((SettingUtils.requestTimeout * 1000).toLong()) //超时时间10s
.cacheMode(CacheMode.NO_CACHE)
.retryCount(SettingUtils.requestRetryTimes) //超时重试的次数
.retryDelay(SettingUtils.requestDelayTime) //超时重试的延迟时间
.retryIncreaseDelay(SettingUtils.requestDelayTime) //超时重试叠加延时
.timeStamp(true)
.execute(object : SimpleCallBack<String>() {
override fun onError(e: ApiException) {
Log.e(TAG, e.detailMessage)
SendUtils.updateLogs(logId, 0, e.displayMessage)
}
override fun onSuccess(response: String) {
Log.i(TAG, response)
SendUtils.updateLogs(logId, 2, response)
}
})
} }

View File

@ -3,6 +3,7 @@ package com.idormy.sms.forwarder.utils.sender
import android.text.TextUtils import android.text.TextUtils
import android.util.Log import android.util.Log
import com.google.gson.Gson import com.google.gson.Gson
import com.idormy.sms.forwarder.R
import com.idormy.sms.forwarder.database.entity.Rule import com.idormy.sms.forwarder.database.entity.Rule
import com.idormy.sms.forwarder.entity.MsgInfo import com.idormy.sms.forwarder.entity.MsgInfo
import com.idormy.sms.forwarder.entity.result.DingtalkResult import com.idormy.sms.forwarder.entity.result.DingtalkResult
@ -15,6 +16,7 @@ import com.xuexiang.xhttp2.XHttp
import com.xuexiang.xhttp2.cache.model.CacheMode import com.xuexiang.xhttp2.cache.model.CacheMode
import com.xuexiang.xhttp2.callback.SimpleCallBack import com.xuexiang.xhttp2.callback.SimpleCallBack
import com.xuexiang.xhttp2.exception.ApiException import com.xuexiang.xhttp2.exception.ApiException
import com.xuexiang.xui.utils.ResUtils.getString
@Suppress("PrivatePropertyName", "UNUSED_PARAMETER") @Suppress("PrivatePropertyName", "UNUSED_PARAMETER")
class WeworkAgentUtils private constructor() { class WeworkAgentUtils private constructor() {
@ -48,9 +50,8 @@ class WeworkAgentUtils private constructor() {
.execute(object : SimpleCallBack<String>() { .execute(object : SimpleCallBack<String>() {
override fun onError(e: ApiException) { override fun onError(e: ApiException) {
SendUtils.updateLogs(logId, 0, e.displayMessage)
Log.e(TAG, e.detailMessage) Log.e(TAG, e.detailMessage)
//XToastUtils.error(e.displayMessage) SendUtils.updateLogs(logId, 0, e.displayMessage)
} }
override fun onSuccess(response: String) { override fun onSuccess(response: String) {
@ -62,7 +63,7 @@ class WeworkAgentUtils private constructor() {
MMKVUtils.put("expires_in_" + setting.agentID, System.currentTimeMillis() + ((resp.expires_in ?: 7200) - 120) * 1000L) //提前2分钟过期 MMKVUtils.put("expires_in_" + setting.agentID, System.currentTimeMillis() + ((resp.expires_in ?: 7200) - 120) * 1000L) //提前2分钟过期
sendTextMsg(setting, msgInfo, rule, logId) sendTextMsg(setting, msgInfo, rule, logId)
} else { } else {
//XToastUtils.error(String.format(getString(R.string.request_failed_tips), response)) SendUtils.updateLogs(logId, 0, String.format(getString(R.string.request_failed_tips), response))
} }
} }
@ -107,9 +108,8 @@ class WeworkAgentUtils private constructor() {
.execute(object : SimpleCallBack<String>() { .execute(object : SimpleCallBack<String>() {
override fun onError(e: ApiException) { override fun onError(e: ApiException) {
SendUtils.updateLogs(logId, 0, e.displayMessage)
Log.e(TAG, e.detailMessage) Log.e(TAG, e.detailMessage)
//XToastUtils.error(e.displayMessage) SendUtils.updateLogs(logId, 0, e.displayMessage)
} }
override fun onSuccess(response: String) { override fun onSuccess(response: String) {
@ -118,10 +118,8 @@ class WeworkAgentUtils private constructor() {
val resp = Gson().fromJson(response, DingtalkResult::class.java) val resp = Gson().fromJson(response, DingtalkResult::class.java)
if (resp.errcode == 0L) { if (resp.errcode == 0L) {
SendUtils.updateLogs(logId, 2, response) SendUtils.updateLogs(logId, 2, response)
//XToastUtils.success(getString(R.string.request_succeeded))
} else { } else {
SendUtils.updateLogs(logId, 0, response) SendUtils.updateLogs(logId, 0, response)
//XToastUtils.error(getString(R.string.request_failed) + response)
} }
} }

View File

@ -56,9 +56,8 @@ class WeworkRobotUtils private constructor() {
.execute(object : SimpleCallBack<String>() { .execute(object : SimpleCallBack<String>() {
override fun onError(e: ApiException) { override fun onError(e: ApiException) {
SendUtils.updateLogs(logId, 0, e.displayMessage)
Log.e(TAG, e.detailMessage) Log.e(TAG, e.detailMessage)
//XToastUtils.error(e.displayMessage) SendUtils.updateLogs(logId, 0, e.displayMessage)
} }
override fun onSuccess(response: String) { override fun onSuccess(response: String) {
@ -67,10 +66,8 @@ class WeworkRobotUtils private constructor() {
val resp = Gson().fromJson(response, WeworkRobotResult::class.java) val resp = Gson().fromJson(response, WeworkRobotResult::class.java)
if (resp.errcode == 0L) { if (resp.errcode == 0L) {
SendUtils.updateLogs(logId, 2, response) SendUtils.updateLogs(logId, 2, response)
//XToastUtils.success(ResUtils.getString(R.string.request_succeeded))
} else { } else {
SendUtils.updateLogs(logId, 0, response) SendUtils.updateLogs(logId, 0, response)
//XToastUtils.error(ResUtils.getString(R.string.request_failed) + response)
} }
} }