优化:移除RxJava

新增:OkHttp重试拦截器、设置超时时间为5秒
This commit is contained in:
pppscn 2022-01-23 13:37:27 +08:00
parent 835591e5dc
commit 31ff05b695
19 changed files with 487 additions and 462 deletions

View File

@ -48,11 +48,13 @@ android {
buildTypes {
release {
minifyEnabled true
shrinkResources true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
signingConfig signingConfigs.release
}
debug {
minifyEnabled true
shrinkResources true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
signingConfig signingConfigs.debug
}
@ -149,8 +151,8 @@ dependencies {
//SDK
implementation 'com.umeng.umsdk:common:9.4.6'//
implementation 'com.umeng.umsdk:asms:1.6.0'// asms包依赖必选
//implementation 'com.umeng.umsdk:apm:1.5.2'// SDKcrash数据请一定集成
//implementation 'com.umeng.umsdk:abtest:1.0.0'//使U-App中ABTest能力
implementation 'com.umeng.umsdk:apm:1.5.2'// U-APM产品包依赖()
//XUpdate
implementation 'com.github.xuexiangjys:XUpdate:2.1.1'
@ -166,13 +168,13 @@ dependencies {
annotationProcessor 'org.projectlombok:lombok:1.18.22'
//RxJava
implementation 'io.reactivex.rxjava3:rxjava:3.1.3'
//implementation 'io.reactivex.rxjava3:rxjava:3.1.3'
//AndroidAsync
implementation 'com.koushikdutta.async:androidasync:3.1.0'
// https://github.com/getActivity/XXPermissions
implementation 'com.github.getActivity:XXPermissions:13.2'
//https://github.com/getActivity/XXPermissions
//implementation 'com.github.getActivity:XXPermissions:13.2'
//jetty
implementation "org.eclipse.jetty:jetty-server:9.2.30.v20200428"

View File

@ -649,7 +649,7 @@ public class SenderActivity extends AppCompatActivity {
try {
SmsVo smsVo = new SmsVo(getString(R.string.test_phone_num), getString(R.string.test_sender_sms), new Date(), getString(R.string.test_sim_info));
SenderMailMsg.sendEmail(0, handler, null, protocol, host, port, ssl, fromEmail, nickname, pwd, toEmail, smsVo.getTitleForSend(title), smsVo.getSmsVoForSend());
SenderMailMsg.sendEmail(0, handler, protocol, host, port, ssl, fromEmail, nickname, pwd, toEmail, smsVo.getTitleForSend(title), smsVo.getSmsVoForSend());
} catch (Exception e) {
Toast.makeText(SenderActivity.this, getString(R.string.failed_to_fwd) + e.getMessage(), Toast.LENGTH_LONG).show();
e.printStackTrace();

View File

@ -0,0 +1,104 @@
package com.idormy.sms.forwarder.sender;
import android.util.Log;
import androidx.annotation.NonNull;
import com.idormy.sms.forwarder.utils.LogUtil;
import java.io.IOException;
import java.io.InterruptedIOException;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
public class RetryIntercepter implements Interceptor {
static final String TAG = "RetryIntercepter";
public int executionCount;//最大重试次数
private final long retryInterval;//重试的间隔
private final long logId;//更新记录ID
RetryIntercepter(Builder builder) {
this.executionCount = builder.executionCount;
this.retryInterval = builder.retryInterval;
this.logId = builder.logId;
}
@NonNull
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Response response = doRequest(chain, request);
int retryNum = 0;
while ((response == null || !response.isSuccessful()) && retryNum <= executionCount) {
Log.w(TAG, "" + retryNum + " 次请求");
if (retryNum > 0) {
final long nextInterval = retryNum * getRetryInterval();
try {
Log.w(TAG, "等待 " + nextInterval + " 秒后重试!");
//noinspection BusyWait
Thread.sleep(nextInterval * 1000);
} catch (final InterruptedException e) {
Thread.currentThread().interrupt();
throw new InterruptedIOException(e.getMessage());
}
}
retryNum++;
response = doRequest(chain, request);
}
if (response == null) throw new InterruptedIOException("服务端无应答");
return response;
}
private Response doRequest(Chain chain, Request request) {
Response response = null;
try {
response = chain.proceed(request);
} catch (Exception e) {
LogUtil.updateLog(logId, 1, e.getMessage());
Log.w(TAG, e.getMessage());
}
return response;
}
/**
* retry间隔时间
*/
public long getRetryInterval() {
return this.retryInterval;
}
public static final class Builder {
private int executionCount;
private long retryInterval;
private long logId;
public Builder() {
executionCount = 3;
retryInterval = 1000;
logId = 0;
}
public RetryIntercepter.Builder executionCount(int executionCount) {
this.executionCount = executionCount;
return this;
}
public RetryIntercepter.Builder retryInterval(long retryInterval) {
this.retryInterval = retryInterval;
return this;
}
public RetryIntercepter.Builder logId(long logId) {
this.logId = logId;
return this;
}
public RetryIntercepter build() {
return new RetryIntercepter(this);
}
}
}

View File

@ -47,10 +47,6 @@ import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.TimeUnit;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.ObservableEmitter;
public class SendUtil {
private static final String TAG = "SendUtil";
@ -174,40 +170,28 @@ public class SendUtil {
@SuppressWarnings("ResultOfMethodCallIgnored")
public static void senderSendMsgNoHandError(SmsVo smsVo, SenderModel senderModel, long logId, String smsTemplate, String regexReplace) {
//网络请求+重试比较耗时创建子线程处理
// new Thread(new Runnable() {
// @Override
// public void run() {
//是否需要失败重试
int retryTimes = SettingUtil.getRetryTimes();
if (retryTimes < 1) {
SendUtil.senderSendMsg(null, null, smsVo, senderModel, logId, smsTemplate, regexReplace);
return;
}
try {
int delayTime = SettingUtil.getDelayTime();
Observable
.create(emitter -> {
Log.w(TAG, "RxJava 开始请求接口...");
SendUtil.senderSendMsg(null, emitter, smsVo, senderModel, logId, smsTemplate, regexReplace);
})
.retryWhen(attempts -> attempts.zipWith(Observable.range(1, retryTimes), (n, i) -> i).flatMap(i -> {
long delay = (long) i * delayTime;
Log.w(TAG, "RxJava 请求接口异常," + delay + "秒后重试");
return Observable.timer(delay, TimeUnit.SECONDS);
}).concatWith(Observable.error(new RuntimeException("请求接口失败,已重试 " + retryTimes + ""))))
.subscribe(
(i) -> System.out.println("onNext with " + i),
(error) -> System.out.println("OnError with " + error)
);
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
// }
// }).start();//启动线程
new Thread(() -> {
try {
//是否需要失败重试
int retryTimes = SettingUtil.getRetryTimes();
if (retryTimes < 1) {
SendUtil.senderSendMsg(null, null, smsVo, senderModel, logId, smsTemplate, regexReplace);
} else {
int delayTime = SettingUtil.getDelayTime();
RetryIntercepter retryInterceptor = new RetryIntercepter.Builder()
.executionCount(retryTimes)
.retryInterval(delayTime)
.logId(logId)
.build();
SendUtil.senderSendMsg(null, retryInterceptor, smsVo, senderModel, logId, smsTemplate, regexReplace);
}
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
}).start();
}
public static void senderSendMsg(Handler handError, ObservableEmitter<Object> emitter, SmsVo smsVo, SenderModel senderModel, long logId, String smsTemplate, String regexReplace) {
public static void senderSendMsg(Handler handError, RetryIntercepter retryInterceptor, SmsVo smsVo, SenderModel senderModel, long logId, String smsTemplate, String regexReplace) {
Log.i(TAG, "senderSendMsg smsVo:" + smsVo.toString() + "senderModel:" + senderModel.toString());
@ -224,7 +208,7 @@ public class SendUtil {
DingDingSettingVo dingDingSettingVo = JSON.parseObject(senderModel.getJsonSetting(), DingDingSettingVo.class);
if (dingDingSettingVo != null) {
try {
SenderDingdingMsg.sendMsg(logId, handError, emitter, dingDingSettingVo.getToken(), dingDingSettingVo.getSecret(), dingDingSettingVo.getAtMobiles(), dingDingSettingVo.getAtAll(), smsVo.getSmsVoForSend(smsTemplate, regexReplace));
SenderDingdingMsg.sendMsg(logId, handError, retryInterceptor, dingDingSettingVo.getToken(), dingDingSettingVo.getSecret(), dingDingSettingVo.getAtMobiles(), dingDingSettingVo.getAtAll(), smsVo.getSmsVoForSend(smsTemplate, regexReplace));
} catch (Exception e) {
LogUtil.updateLog(logId, 0, e.getMessage());
Log.e(TAG, "senderSendMsg: dingding error " + e.getMessage());
@ -239,7 +223,7 @@ public class SendUtil {
EmailSettingVo emailSettingVo = JSON.parseObject(senderModel.getJsonSetting(), EmailSettingVo.class);
if (emailSettingVo != null) {
try {
SenderMailMsg.sendEmail(logId, handError, emitter, emailSettingVo.getProtocol(), emailSettingVo.getHost(), emailSettingVo.getPort(), emailSettingVo.getSsl(), emailSettingVo.getFromEmail(), emailSettingVo.getNickname(),
SenderMailMsg.sendEmail(logId, handError, emailSettingVo.getProtocol(), emailSettingVo.getHost(), emailSettingVo.getPort(), emailSettingVo.getSsl(), emailSettingVo.getFromEmail(), emailSettingVo.getNickname(),
emailSettingVo.getPwd(), emailSettingVo.getToEmail(), smsVo.getTitleForSend(emailSettingVo.getTitle(), regexReplace), smsVo.getSmsVoForSend(smsTemplate, regexReplace));
} catch (Exception e) {
LogUtil.updateLog(logId, 0, e.getMessage());
@ -255,7 +239,7 @@ public class SendUtil {
BarkSettingVo barkSettingVo = JSON.parseObject(senderModel.getJsonSetting(), BarkSettingVo.class);
if (barkSettingVo != null) {
try {
SenderBarkMsg.sendMsg(logId, handError, emitter, barkSettingVo.getServer(), barkSettingVo.getIcon(), smsVo.getMobile(), smsVo.getSmsVoForSend(smsTemplate, regexReplace), senderModel.getName());
SenderBarkMsg.sendMsg(logId, handError, retryInterceptor, barkSettingVo.getServer(), barkSettingVo.getIcon(), smsVo.getMobile(), smsVo.getSmsVoForSend(smsTemplate, regexReplace), senderModel.getName());
} catch (Exception e) {
LogUtil.updateLog(logId, 0, e.getMessage());
Log.e(TAG, "senderSendMsg: SenderBarkMsg error " + e.getMessage());
@ -270,7 +254,7 @@ public class SendUtil {
WebNotifySettingVo webNotifySettingVo = JSON.parseObject(senderModel.getJsonSetting(), WebNotifySettingVo.class);
if (webNotifySettingVo != null) {
try {
SenderWebNotifyMsg.sendMsg(logId, handError, emitter, webNotifySettingVo.getWebServer(), webNotifySettingVo.getWebParams(), webNotifySettingVo.getSecret(), webNotifySettingVo.getMethod(), smsVo.getMobile(), smsVo.getSmsVoForSend(smsTemplate, regexReplace));
SenderWebNotifyMsg.sendMsg(logId, handError, retryInterceptor, webNotifySettingVo.getWebServer(), webNotifySettingVo.getWebParams(), webNotifySettingVo.getSecret(), webNotifySettingVo.getMethod(), smsVo.getMobile(), smsVo.getSmsVoForSend(smsTemplate, regexReplace));
} catch (Exception e) {
LogUtil.updateLog(logId, 0, e.getMessage());
Log.e(TAG, "senderSendMsg: SenderWebNotifyMsg error " + e.getMessage());
@ -285,7 +269,7 @@ public class SendUtil {
QYWXGroupRobotSettingVo qywxGroupRobotSettingVo = JSON.parseObject(senderModel.getJsonSetting(), QYWXGroupRobotSettingVo.class);
if (qywxGroupRobotSettingVo != null) {
try {
SenderQyWxGroupRobotMsg.sendMsg(logId, handError, emitter, qywxGroupRobotSettingVo.getWebHook(), smsVo.getMobile(), smsVo.getSmsVoForSend(smsTemplate, regexReplace));
SenderQyWxGroupRobotMsg.sendMsg(logId, handError, retryInterceptor, qywxGroupRobotSettingVo.getWebHook(), smsVo.getMobile(), smsVo.getSmsVoForSend(smsTemplate, regexReplace));
} catch (Exception e) {
LogUtil.updateLog(logId, 0, e.getMessage());
Log.e(TAG, "senderSendMsg: SenderQyWxGroupRobotMsg error " + e.getMessage());
@ -300,7 +284,7 @@ public class SendUtil {
QYWXAppSettingVo qYWXAppSettingVo = JSON.parseObject(senderModel.getJsonSetting(), QYWXAppSettingVo.class);
if (qYWXAppSettingVo != null) {
try {
SenderQyWxAppMsg.sendMsg(logId, handError, emitter, senderModel, qYWXAppSettingVo, smsVo.getSmsVoForSend(smsTemplate, regexReplace));
SenderQyWxAppMsg.sendMsg(logId, handError, retryInterceptor, senderModel, qYWXAppSettingVo, smsVo.getSmsVoForSend(smsTemplate, regexReplace));
} catch (Exception e) {
LogUtil.updateLog(logId, 0, e.getMessage());
Log.e(TAG, "senderSendMsg: qywx_app error " + e.getMessage());
@ -315,7 +299,7 @@ public class SendUtil {
ServerChanSettingVo serverChanSettingVo = JSON.parseObject(senderModel.getJsonSetting(), ServerChanSettingVo.class);
if (serverChanSettingVo != null) {
try {
SenderServerChanMsg.sendMsg(logId, handError, emitter, serverChanSettingVo.getSendKey(), smsVo.getMobile(), smsVo.getSmsVoForSend(smsTemplate, regexReplace));
SenderServerChanMsg.sendMsg(logId, handError, retryInterceptor, serverChanSettingVo.getSendKey(), smsVo.getMobile(), smsVo.getSmsVoForSend(smsTemplate, regexReplace));
} catch (Exception e) {
LogUtil.updateLog(logId, 0, e.getMessage());
Log.e(TAG, "senderSendMsg: SenderServerChanMsg error " + e.getMessage());
@ -330,7 +314,7 @@ public class SendUtil {
TelegramSettingVo telegramSettingVo = JSON.parseObject(senderModel.getJsonSetting(), TelegramSettingVo.class);
if (telegramSettingVo != null) {
try {
SenderTelegramMsg.sendMsg(logId, handError, emitter, telegramSettingVo, smsVo.getMobile(), smsVo.getSmsVoForSend(smsTemplate, regexReplace), telegramSettingVo.getMethod());
SenderTelegramMsg.sendMsg(logId, handError, retryInterceptor, telegramSettingVo, smsVo.getMobile(), smsVo.getSmsVoForSend(smsTemplate, regexReplace), telegramSettingVo.getMethod());
} catch (Exception e) {
LogUtil.updateLog(logId, 0, e.getMessage());
Log.e(TAG, "senderSendMsg: SenderTelegramMsg error " + e.getMessage());
@ -372,7 +356,7 @@ public class SendUtil {
FeiShuSettingVo feiShuSettingVo = JSON.parseObject(senderModel.getJsonSetting(), FeiShuSettingVo.class);
if (feiShuSettingVo != null) {
try {
SenderFeishuMsg.sendMsg(logId, handError, emitter, feiShuSettingVo.getWebhook(), feiShuSettingVo.getSecret(), smsVo.getMobile(), smsVo.getDate(), smsVo.getSmsVoForSend(smsTemplate, regexReplace));
SenderFeishuMsg.sendMsg(logId, handError, retryInterceptor, feiShuSettingVo.getWebhook(), feiShuSettingVo.getSecret(), smsVo.getMobile(), smsVo.getDate(), smsVo.getSmsVoForSend(smsTemplate, regexReplace));
} catch (Exception e) {
LogUtil.updateLog(logId, 0, e.getMessage());
Log.e(TAG, "senderSendMsg: feishu error " + e.getMessage());
@ -387,7 +371,7 @@ public class SendUtil {
PushPlusSettingVo pushPlusSettingVo = JSON.parseObject(senderModel.getJsonSetting(), PushPlusSettingVo.class);
if (pushPlusSettingVo != null) {
try {
SenderPushPlusMsg.sendMsg(logId, handError, emitter, pushPlusSettingVo, smsVo.getMobile(), smsVo.getSmsVoForSend(smsTemplate, regexReplace));
SenderPushPlusMsg.sendMsg(logId, handError, retryInterceptor, pushPlusSettingVo, smsVo.getMobile(), smsVo.getSmsVoForSend(smsTemplate, regexReplace));
} catch (Exception e) {
LogUtil.updateLog(logId, 0, e.getMessage());
Log.e(TAG, "senderSendMsg: feishu error " + e.getMessage());
@ -402,7 +386,7 @@ public class SendUtil {
GotifySettingVo gotifySettingVo = JSON.parseObject(senderModel.getJsonSetting(), GotifySettingVo.class);
if (gotifySettingVo != null) {
try {
SenderGotifyMsg.sendMsg(logId, handError, emitter, gotifySettingVo, smsVo.getMobile(), smsVo.getSmsVoForSend(smsTemplate, regexReplace));
SenderGotifyMsg.sendMsg(logId, handError, retryInterceptor, gotifySettingVo, smsVo.getMobile(), smsVo.getSmsVoForSend(smsTemplate, regexReplace));
} catch (Exception e) {
LogUtil.updateLog(logId, 0, e.getMessage());
Log.e(TAG, "senderSendMsg: gotify error " + e.getMessage());

View File

@ -3,19 +3,16 @@ package com.idormy.sms.forwarder.sender;
import android.os.Handler;
import android.util.Log;
import androidx.annotation.NonNull;
import com.idormy.sms.forwarder.utils.Define;
import com.idormy.sms.forwarder.utils.LogUtil;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import io.reactivex.rxjava3.core.ObservableEmitter;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
@ -24,7 +21,7 @@ public class SenderBarkMsg extends SenderBaseMsg {
static final String TAG = "SenderBarkMsg";
public static void sendMsg(final long logId, final Handler handError, final ObservableEmitter<Object> emitter, String barkServer, String barkIcon, String from, String content, String groupName) throws Exception {
public static void sendMsg(final long logId, final Handler handError, final RetryIntercepter retryInterceptor, String barkServer, String barkIcon, String from, String content, String groupName) throws Exception {
Log.i(TAG, "sendMsg barkServer:" + barkServer + " from:" + from + " content:" + content);
if (barkServer == null || barkServer.isEmpty()) {
@ -55,31 +52,32 @@ public class SenderBarkMsg extends SenderBaseMsg {
final String requestUrl = barkServer;
Log.i(TAG, "requestUrl:" + requestUrl);
OkHttpClient client = new OkHttpClient();
OkHttpClient.Builder builder = new OkHttpClient.Builder();
//设置重试拦截器
//if (retryInterceptor != null) builder.addInterceptor(retryInterceptor);
//设置读取超时时间
OkHttpClient client = builder
.readTimeout(Define.REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS)
.writeTimeout(Define.REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS)
.connectTimeout(Define.REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS)
.build();
final Request request = new Request.Builder().url(requestUrl).get().build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(@NonNull Call call, @NonNull final IOException e) {
LogUtil.updateLog(logId, 0, e.getMessage());
Toast(handError, TAG, "发送失败:" + e.getMessage());
if (emitter != null) emitter.onError(new Exception("RxJava 请求接口异常..."));
}
@Override
public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
final String responseStr = Objects.requireNonNull(response.body()).string();
Log.d(TAG, "Response" + response.code() + "" + responseStr);
Toast(handError, TAG, "发送状态:" + responseStr);
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
//TODO:粗略解析是否发送成功
if (responseStr.contains("\"message\":\"success\"")) {
LogUtil.updateLog(logId, 2, responseStr);
} else {
LogUtil.updateLog(logId, 0, responseStr);
}
final String responseStr = Objects.requireNonNull(response.body()).string();
Log.d(TAG, "Response" + response.code() + "" + responseStr);
Toast(handError, TAG, "发送状态:" + responseStr);
//TODO:粗略解析是否发送成功
if (responseStr.contains("\"message\":\"success\"")) {
LogUtil.updateLog(logId, 2, responseStr);
} else {
LogUtil.updateLog(logId, 0, responseStr);
}
});
}
}

View File

@ -5,9 +5,8 @@ import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import androidx.annotation.NonNull;
import com.alibaba.fastjson.JSON;
import com.idormy.sms.forwarder.utils.Define;
import com.idormy.sms.forwarder.utils.LogUtil;
import java.io.IOException;
@ -18,13 +17,11 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import io.reactivex.rxjava3.core.ObservableEmitter;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
@ -36,7 +33,7 @@ public class SenderDingdingMsg extends SenderBaseMsg {
static final String TAG = "SenderDingdingMsg";
public static void sendMsg(final long logId, final Handler handError, final ObservableEmitter<Object> emitter, String token, String secret, String atMobiles, Boolean atAll, String content) throws Exception {
public static void sendMsg(final long logId, final Handler handError, final RetryIntercepter retryInterceptor, String token, String secret, String atMobiles, Boolean atAll, String content) throws Exception {
Log.i(TAG, "sendMsg token:" + token + " secret:" + secret + " atMobiles:" + atMobiles + " atAll:" + atAll + " content:" + content);
if (token == null || token.isEmpty()) {
@ -88,7 +85,16 @@ public class SenderDingdingMsg extends SenderBaseMsg {
final String requestMsg = JSON.toJSONString(textMsgMap);
Log.i(TAG, "requestMsg:" + requestMsg);
OkHttpClient client = new OkHttpClient();
OkHttpClient.Builder builder = new OkHttpClient.Builder();
//设置重试拦截器
if (retryInterceptor != null) builder.addInterceptor(retryInterceptor);
//设置读取超时时间
OkHttpClient client = builder
.readTimeout(Define.REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS)
.writeTimeout(Define.REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS)
.connectTimeout(Define.REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS)
.build();
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), requestMsg);
final Request request = new Request.Builder()
@ -96,31 +102,22 @@ public class SenderDingdingMsg extends SenderBaseMsg {
.addHeader("Content-Type", "application/json; charset=utf-8")
.post(requestBody)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(@NonNull Call call, @NonNull final IOException e) {
LogUtil.updateLog(logId, 0, e.getMessage());
Toast(handError, TAG, "发送失败:" + e.getMessage());
if (emitter != null) emitter.onError(new Exception("RxJava 请求接口异常..."));
}
@Override
public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
final String responseStr = Objects.requireNonNull(response.body()).string();
Log.d(TAG, "Response" + response.code() + "" + responseStr);
Toast(handError, TAG, "发送状态:" + responseStr);
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
//TODO:粗略解析是否发送成功
if (responseStr.contains("\"errcode\":0")) {
LogUtil.updateLog(logId, 2, responseStr);
} else {
LogUtil.updateLog(logId, 0, responseStr);
}
final String responseStr = Objects.requireNonNull(response.body()).string();
Log.d(TAG, "Response" + response.code() + "" + responseStr);
Toast(handError, TAG, "发送状态:" + responseStr);
//TODO:粗略解析是否发送成功
if (responseStr.contains("\"errcode\":0")) {
LogUtil.updateLog(logId, 2, responseStr);
} else {
LogUtil.updateLog(logId, 0, responseStr);
}
});
}
}
}
}

View File

@ -4,9 +4,8 @@ import android.os.Handler;
import android.util.Base64;
import android.util.Log;
import androidx.annotation.NonNull;
import com.alibaba.fastjson.JSON;
import com.idormy.sms.forwarder.utils.Define;
import com.idormy.sms.forwarder.utils.LogUtil;
import com.idormy.sms.forwarder.utils.SettingUtil;
@ -18,13 +17,11 @@ import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import io.reactivex.rxjava3.core.ObservableEmitter;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
@ -89,8 +86,7 @@ public class SenderFeishuMsg extends SenderBaseMsg {
" }\n" +
"}";
//@SuppressWarnings("rawtypes")
public static void sendMsg(final long logId, final Handler handError, final ObservableEmitter<Object> emitter, String webhook, String secret, String from, Date date, String content) throws Exception {
public static void sendMsg(final long logId, final Handler handError, final RetryIntercepter retryInterceptor, String webhook, String secret, String from, Date date, String content) throws Exception {
Log.i(TAG, "sendMsg webhook:" + webhook + " secret:" + secret + " content:" + content);
if (webhook == null || webhook.isEmpty()) {
@ -124,7 +120,16 @@ public class SenderFeishuMsg extends SenderBaseMsg {
final String requestMsg = JSON.toJSONString(textMsgMap).replace("\"${CARD_BODY}\"", buildMsg(from, date, content));
Log.i(TAG, "requestMsg:" + requestMsg);
OkHttpClient client = new OkHttpClient();
OkHttpClient.Builder builder = new OkHttpClient.Builder();
//设置重试拦截器
if (retryInterceptor != null) builder.addInterceptor(retryInterceptor);
//设置读取超时时间
OkHttpClient client = builder
.readTimeout(Define.REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS)
.writeTimeout(Define.REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS)
.connectTimeout(Define.REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS)
.build();
@SuppressWarnings("deprecation") RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), requestMsg);
final Request request = new Request.Builder()
@ -132,29 +137,20 @@ public class SenderFeishuMsg extends SenderBaseMsg {
.addHeader("Content-Type", "application/json; charset=utf-8")
.post(requestBody)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(@NonNull Call call, @NonNull final IOException e) {
LogUtil.updateLog(logId, 0, e.getMessage());
Toast(handError, TAG, "发送失败:" + e.getMessage());
if (emitter != null) emitter.onError(new Exception("RxJava 请求接口异常..."));
}
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
@Override
public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
final String responseStr = Objects.requireNonNull(response.body()).string();
Log.d(TAG, "Response" + response.code() + "" + responseStr);
Toast(handError, TAG, "发送状态:" + responseStr);
final String responseStr = Objects.requireNonNull(response.body()).string();
Log.d(TAG, "Response" + response.code() + "" + responseStr);
Toast(handError, TAG, "发送状态:" + responseStr);
//TODO:粗略解析是否发送成功
if (responseStr.contains("\"StatusCode\":0")) {
LogUtil.updateLog(logId, 2, responseStr);
} else {
LogUtil.updateLog(logId, 0, responseStr);
}
//TODO:粗略解析是否发送成功
if (responseStr.contains("\"StatusCode\":0")) {
LogUtil.updateLog(logId, 2, responseStr);
} else {
LogUtil.updateLog(logId, 0, responseStr);
}
});
}
}

View File

@ -3,17 +3,14 @@ package com.idormy.sms.forwarder.sender;
import android.os.Handler;
import android.util.Log;
import androidx.annotation.NonNull;
import com.idormy.sms.forwarder.model.vo.GotifySettingVo;
import com.idormy.sms.forwarder.utils.Define;
import com.idormy.sms.forwarder.utils.LogUtil;
import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import io.reactivex.rxjava3.core.ObservableEmitter;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
@ -24,7 +21,7 @@ public class SenderGotifyMsg extends SenderBaseMsg {
static final String TAG = "SenderGotifyMsg";
public static void sendMsg(final long logId, final Handler handError, final ObservableEmitter<Object> emitter, GotifySettingVo gotifySettingVo, String title, String message) throws Exception {
public static void sendMsg(final long logId, final Handler handError, final RetryIntercepter retryInterceptor, GotifySettingVo gotifySettingVo, String title, String message) throws Exception {
//具体消息内容
if (message == null || message.isEmpty()) return;
@ -38,31 +35,31 @@ public class SenderGotifyMsg extends SenderBaseMsg {
String requestUrl = gotifySettingVo.getWebServer();
Log.i(TAG, "requestUrl:" + requestUrl);
OkHttpClient.Builder builder = new OkHttpClient.Builder();
//设置重试拦截器
if (retryInterceptor != null) builder.addInterceptor(retryInterceptor);
//设置读取超时时间
OkHttpClient client = builder
.readTimeout(Define.REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS)
.writeTimeout(Define.REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS)
.connectTimeout(Define.REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS)
.build();
Request request = new Request.Builder().url(requestUrl).post(formBody).build();
OkHttpClient client = new OkHttpClient();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(@NonNull Call call, @NonNull final IOException e) {
LogUtil.updateLog(logId, 0, e.getMessage());
Toast(handError, TAG, "发送失败:" + e.getMessage());
if (emitter != null) emitter.onError(new RuntimeException("RxJava 请求接口异常..."));
}
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
@Override
public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
final String responseStr = Objects.requireNonNull(response.body()).string();
Log.d(TAG, "Response" + response.code() + "" + responseStr);
Toast(handError, TAG, "发送状态:" + responseStr);
final String responseStr = Objects.requireNonNull(response.body()).string();
Log.d(TAG, "Response" + response.code() + "" + responseStr);
Toast(handError, TAG, "发送状态:" + responseStr);
//TODO:粗略解析是否发送成功
if (response.code() == 200) {
LogUtil.updateLog(logId, 2, responseStr);
} else {
LogUtil.updateLog(logId, 1, responseStr);
}
//TODO:粗略解析是否发送成功
if (response.isSuccessful()) {
LogUtil.updateLog(logId, 2, responseStr);
} else {
LogUtil.updateLog(logId, 1, responseStr);
}
});
}
}

View File

@ -12,13 +12,11 @@ import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import io.reactivex.rxjava3.core.ObservableEmitter;
public class SenderMailMsg extends SenderBaseMsg {
private static final String TAG = "SenderMailMsg";
public static void sendEmail(final long logId, final Handler handError, final ObservableEmitter<Object> emitter, final String protocol, final String host, final String port, final boolean ssl, final String fromEmail, final String nickname, final String pwd, final String toAdd, final String title, final String content) {
public static void sendEmail(final long logId, final Handler handError, final String protocol, final String host, final String port, final boolean ssl, final String fromEmail, final String nickname, final String pwd, final String toAdd, final String title, final String content) {
Log.d(TAG, "sendEmail: protocol:" + protocol + " host:" + host + " port:" + port + " ssl:" + ssl + " fromEmail:" + fromEmail + " nickname:" + nickname + " pwd:" + pwd + " toAdd:" + toAdd);
@ -65,7 +63,7 @@ public class SenderMailMsg extends SenderBaseMsg {
LogUtil.updateLog(logId, 0, e.getMessage());
Log.e(TAG, e.getMessage(), e);
Toast(handError, TAG, "发送失败:" + e.getMessage());
if (emitter != null) emitter.onError(new Exception("RxJava 请求接口异常..."));
}
}
}

View File

@ -3,20 +3,17 @@ package com.idormy.sms.forwarder.sender;
import android.os.Handler;
import android.util.Log;
import androidx.annotation.NonNull;
import com.alibaba.fastjson.JSON;
import com.idormy.sms.forwarder.model.vo.PushPlusSettingVo;
import com.idormy.sms.forwarder.utils.Define;
import com.idormy.sms.forwarder.utils.LogUtil;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import io.reactivex.rxjava3.core.ObservableEmitter;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
@ -28,7 +25,7 @@ public class SenderPushPlusMsg extends SenderBaseMsg {
static final String TAG = "SenderPushPlusMsg";
public static void sendMsg(final long logId, final Handler handError, final ObservableEmitter<Object> emitter, PushPlusSettingVo pushPlusSettingVo, String title, String content) throws Exception {
public static void sendMsg(final long logId, final Handler handError, final RetryIntercepter retryInterceptor, PushPlusSettingVo pushPlusSettingVo, String title, String content) throws Exception {
//用户令牌
String token = pushPlusSettingVo.getToken();
@ -74,7 +71,16 @@ public class SenderPushPlusMsg extends SenderBaseMsg {
final String requestMsg = JSON.toJSONString(textMsgMap);
Log.i(TAG, "requestMsg:" + requestMsg);
OkHttpClient client = new OkHttpClient();
OkHttpClient.Builder builder = new OkHttpClient.Builder();
//设置重试拦截器
if (retryInterceptor != null) builder.addInterceptor(retryInterceptor);
//设置读取超时时间
OkHttpClient client = builder
.readTimeout(Define.REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS)
.writeTimeout(Define.REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS)
.connectTimeout(Define.REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS)
.build();
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), requestMsg);
final Request request = new Request.Builder()
@ -82,29 +88,21 @@ public class SenderPushPlusMsg extends SenderBaseMsg {
.addHeader("Content-Type", "application/json; charset=utf-8")
.post(requestBody)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(@NonNull Call call, @NonNull final IOException e) {
LogUtil.updateLog(logId, 0, e.getMessage());
Toast(handError, TAG, "发送失败:" + e.getMessage());
if (emitter != null) emitter.onError(new Exception("RxJava 请求接口异常..."));
}
@Override
public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
final String responseStr = Objects.requireNonNull(response.body()).string();
Log.d(TAG, "Response" + response.code() + "" + responseStr);
Toast(handError, TAG, "发送状态:" + responseStr);
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
//TODO:粗略解析是否发送成功
if (responseStr.contains("\"code\":200")) {
LogUtil.updateLog(logId, 2, responseStr);
} else {
LogUtil.updateLog(logId, 0, responseStr);
}
final String responseStr = Objects.requireNonNull(response.body()).string();
Log.d(TAG, "Response" + response.code() + "" + responseStr);
Toast(handError, TAG, "发送状态:" + responseStr);
//TODO:粗略解析是否发送成功
if (responseStr.contains("\"code\":200")) {
LogUtil.updateLog(logId, 2, responseStr);
} else {
LogUtil.updateLog(logId, 0, responseStr);
}
});
}
}

View File

@ -1,28 +1,21 @@
package com.idormy.sms.forwarder.sender;
import static com.idormy.sms.forwarder.SenderActivity.NOTIFY;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import androidx.annotation.NonNull;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.idormy.sms.forwarder.model.SenderModel;
import com.idormy.sms.forwarder.model.vo.QYWXAppSettingVo;
import com.idormy.sms.forwarder.utils.Define;
import com.idormy.sms.forwarder.utils.LogUtil;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import io.reactivex.rxjava3.core.ObservableEmitter;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
@ -34,7 +27,7 @@ public class SenderQyWxAppMsg extends SenderBaseMsg {
static final String TAG = "SenderQyWxAppMsg";
public static void sendMsg(final long logId, final Handler handError, final ObservableEmitter<Object> emitter, final SenderModel senderModel, final QYWXAppSettingVo qYWXAppSettingVo, String content) throws Exception {
public static void sendMsg(final long logId, final Handler handError, final RetryIntercepter retryInterceptor, final SenderModel senderModel, final QYWXAppSettingVo qYWXAppSettingVo, String content) throws Exception {
if (qYWXAppSettingVo == null) {
Toast(handError, TAG, "参数错误");
@ -62,78 +55,67 @@ public class SenderQyWxAppMsg extends SenderBaseMsg {
getTokenUrl += "&corpsecret=" + secret;
Log.d(TAG, "getTokenUrl" + getTokenUrl);
OkHttpClient client = new OkHttpClient();
OkHttpClient.Builder builder = new OkHttpClient.Builder();
//设置重试拦截器
if (retryInterceptor != null) builder.addInterceptor(retryInterceptor);
//设置读取超时时间
OkHttpClient client = builder
.readTimeout(Define.REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS)
.writeTimeout(Define.REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS)
.connectTimeout(Define.REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS)
.build();
final Request request = new Request.Builder().url(getTokenUrl).get().build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(@NonNull Call call, @NonNull final IOException e) {
LogUtil.updateLog(logId, 0, e.getMessage());
try (Response response = client.newCall(request).execute()) {
//异常处理
if (!response.isSuccessful()) {
String resp = "Unexpected code " + response;
Log.d(TAG, "onFailure" + resp);
Toast(handError, TAG, "获取access_token失败" + resp);
LogUtil.updateLog(logId, 0, resp);
qYWXAppSettingVo.setAccessToken("");
qYWXAppSettingVo.setExpiresIn(0L);
if (senderModel != null) {
senderModel.setJsonSetting(JSON.toJSONString(qYWXAppSettingVo));
SenderUtil.updateSender(senderModel);
}
Log.d(TAG, "onFailure" + e.getMessage());
if (handError != null) {
Message msg = new Message();
msg.what = NOTIFY;
Bundle bundle = new Bundle();
bundle.putString("DATA", "获取access_token失败" + e.getMessage());
msg.setData(bundle);
handError.sendMessage(msg);
if (emitter != null) emitter.onError(new Exception("RxJava 请求接口异常..."));
}
}
@Override
public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
final String json = Objects.requireNonNull(response.body()).string();
Log.d(TAG, "Code" + response.code() + " Response: " + json);
JSONObject jsonObject = JSON.parseObject(json);
int errcode = jsonObject.getInteger("errcode");
if (errcode == 0) {
String access_token = jsonObject.getString("access_token");
long expires_in = System.currentTimeMillis() + (jsonObject.getInteger("expires_in") - 120) * 1000L; //提前2分钟过期
Log.d(TAG, "access_token" + access_token);
Log.d(TAG, "expires_in" + expires_in);
final String json = Objects.requireNonNull(response.body()).string();
Log.d(TAG, "Code" + response.code() + " Response: " + json);
JSONObject jsonObject = JSON.parseObject(json);
int errcode = jsonObject.getInteger("errcode");
if (errcode == 0) {
String access_token = jsonObject.getString("access_token");
long expires_in = System.currentTimeMillis() + (jsonObject.getInteger("expires_in") - 120) * 1000L; //提前2分钟过期
Log.d(TAG, "access_token" + access_token);
Log.d(TAG, "expires_in" + expires_in);
qYWXAppSettingVo.setAccessToken(access_token);
qYWXAppSettingVo.setExpiresIn(expires_in);
if (senderModel != null) {
senderModel.setJsonSetting(JSON.toJSONString(qYWXAppSettingVo));
SenderUtil.updateSender(senderModel);
}
sendTextMsg(emitter, logId, handError, agentID, toUser, content, access_token);
} else {
String errmsg = jsonObject.getString("errmsg");
LogUtil.updateLog(logId, 0, errmsg);
Log.d(TAG, "onFailure" + errmsg);
if (handError != null) {
Message msg = new Message();
msg.what = NOTIFY;
Bundle bundle = new Bundle();
bundle.putString("DATA", "获取access_token失败" + errmsg);
msg.setData(bundle);
handError.sendMessage(msg);
}
if (emitter != null) emitter.onError(new Exception("RxJava 请求接口异常..."));
qYWXAppSettingVo.setAccessToken(access_token);
qYWXAppSettingVo.setExpiresIn(expires_in);
if (senderModel != null) {
senderModel.setJsonSetting(JSON.toJSONString(qYWXAppSettingVo));
SenderUtil.updateSender(senderModel);
}
}
});
sendTextMsg(retryInterceptor, logId, handError, agentID, toUser, content, access_token);
} else {
String errmsg = jsonObject.getString("errmsg");
LogUtil.updateLog(logId, 0, errmsg);
Log.d(TAG, "onFailure" + errmsg);
Toast(handError, TAG, "获取access_token失败" + errmsg);
}
}
} else {
sendTextMsg(emitter, logId, handError, agentID, toUser, content, accessToken);
sendTextMsg(retryInterceptor, logId, handError, agentID, toUser, content, accessToken);
}
}
//发送文本消息
public static void sendTextMsg(ObservableEmitter<Object> emitter, final long logId, final Handler handError, String agentID, String toUser, String content, String accessToken) {
public static void sendTextMsg(RetryIntercepter retryInterceptor, final long logId, final Handler handError, String agentID, String toUser, String content, String accessToken) throws Exception {
Map textMsgMap = new HashMap();
textMsgMap.put("touser", toUser);
@ -149,8 +131,16 @@ public class SenderQyWxAppMsg extends SenderBaseMsg {
final String requestMsg = JSON.toJSONString(textMsgMap);
Log.i(TAG, "requestMsg:" + requestMsg);
OkHttpClient.Builder builder = new OkHttpClient.Builder();
//设置重试拦截器
if (retryInterceptor != null) builder.addInterceptor(retryInterceptor);
//设置读取超时时间
OkHttpClient client = builder
.readTimeout(Define.REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS)
.writeTimeout(Define.REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS)
.connectTimeout(Define.REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS)
.build();
OkHttpClient client = new OkHttpClient();
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), requestMsg);
final Request request = new Request.Builder()
@ -158,29 +148,21 @@ public class SenderQyWxAppMsg extends SenderBaseMsg {
.addHeader("Content-Type", "application/json; charset=utf-8")
.post(requestBody)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(@NonNull Call call, @NonNull final IOException e) {
LogUtil.updateLog(logId, 0, e.getMessage());
Toast(handError, TAG, "发送失败:" + e.getMessage());
if (emitter != null) emitter.onError(new Exception("RxJava 请求接口异常..."));
}
@Override
public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
final String responseStr = Objects.requireNonNull(response.body()).string();
Log.d(TAG, "Response" + response.code() + "" + responseStr);
Toast(handError, TAG, "发送状态:" + responseStr);
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
//TODO:粗略解析是否发送成功
if (responseStr.contains("\"errcode\":0")) {
LogUtil.updateLog(logId, 2, responseStr);
} else {
LogUtil.updateLog(logId, 0, responseStr);
}
final String responseStr = Objects.requireNonNull(response.body()).string();
Log.d(TAG, "Response" + response.code() + "" + responseStr);
Toast(handError, TAG, "发送状态:" + responseStr);
//TODO:粗略解析是否发送成功
if (responseStr.contains("\"errcode\":0")) {
LogUtil.updateLog(logId, 2, responseStr);
} else {
LogUtil.updateLog(logId, 0, responseStr);
}
});
}
}

View File

@ -3,19 +3,16 @@ package com.idormy.sms.forwarder.sender;
import android.os.Handler;
import android.util.Log;
import androidx.annotation.NonNull;
import com.alibaba.fastjson.JSON;
import com.idormy.sms.forwarder.utils.Define;
import com.idormy.sms.forwarder.utils.LogUtil;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import io.reactivex.rxjava3.core.ObservableEmitter;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
@ -27,7 +24,7 @@ public class SenderQyWxGroupRobotMsg extends SenderBaseMsg {
static final String TAG = "SenderQyWxGroupRobotMsg";
public static void sendMsg(final long logId, final Handler handError, final ObservableEmitter<Object> emitter, String webHook, String from, String content) throws Exception {
public static void sendMsg(final long logId, final Handler handError, final RetryIntercepter retryInterceptor, String webHook, String from, String content) throws Exception {
Log.i(TAG, "sendMsg webHook:" + webHook + " from:" + from + " content:" + content);
if (webHook == null || webHook.isEmpty()) {
@ -44,7 +41,16 @@ public class SenderQyWxGroupRobotMsg extends SenderBaseMsg {
final String requestMsg = JSON.toJSONString(textMsgMap);
Log.i(TAG, "requestMsg:" + requestMsg);
OkHttpClient client = new OkHttpClient();
OkHttpClient.Builder builder = new OkHttpClient.Builder();
//设置重试拦截器
if (retryInterceptor != null) builder.addInterceptor(retryInterceptor);
//设置读取超时时间
OkHttpClient client = builder
.readTimeout(Define.REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS)
.writeTimeout(Define.REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS)
.connectTimeout(Define.REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS)
.build();
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), requestMsg);
final Request request = new Request.Builder()
@ -52,29 +58,21 @@ public class SenderQyWxGroupRobotMsg extends SenderBaseMsg {
.addHeader("Content-Type", "application/json; charset=utf-8")
.post(requestBody)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(@NonNull Call call, @NonNull final IOException e) {
LogUtil.updateLog(logId, 0, e.getMessage());
Toast(handError, TAG, "发送失败:" + e.getMessage());
if (emitter != null) emitter.onError(new Exception("RxJava 请求接口异常..."));
}
@Override
public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
final String responseStr = Objects.requireNonNull(response.body()).string();
Log.d(TAG, "Response" + response.code() + "" + responseStr);
Toast(handError, TAG, "发送状态:" + responseStr);
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
//TODO:粗略解析是否发送成功
if (responseStr.contains("\"errcode\":0")) {
LogUtil.updateLog(logId, 2, responseStr);
} else {
LogUtil.updateLog(logId, 0, responseStr);
}
final String responseStr = Objects.requireNonNull(response.body()).string();
Log.d(TAG, "Response" + response.code() + "" + responseStr);
Toast(handError, TAG, "发送状态:" + responseStr);
//TODO:粗略解析是否发送成功
if (responseStr.contains("\"errcode\":0")) {
LogUtil.updateLog(logId, 2, responseStr);
} else {
LogUtil.updateLog(logId, 0, responseStr);
}
});
}
}

View File

@ -3,16 +3,13 @@ package com.idormy.sms.forwarder.sender;
import android.os.Handler;
import android.util.Log;
import androidx.annotation.NonNull;
import com.idormy.sms.forwarder.utils.Define;
import com.idormy.sms.forwarder.utils.LogUtil;
import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import io.reactivex.rxjava3.core.ObservableEmitter;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
@ -23,7 +20,7 @@ public class SenderServerChanMsg extends SenderBaseMsg {
static final String TAG = "SenderServerChanMsg";
public static void sendMsg(final long logId, final Handler handError, final ObservableEmitter<Object> emitter, final String sendKey, final String title, final String desp) throws Exception {
public static void sendMsg(final long logId, final Handler handError, final RetryIntercepter retryInterceptor, final String sendKey, final String title, final String desp) throws Exception {
Log.i(TAG, "sendMsg sendKey:" + sendKey + " title:" + title + " desp:" + desp);
if (sendKey == null || sendKey.isEmpty()) {
@ -36,36 +33,37 @@ public class SenderServerChanMsg extends SenderBaseMsg {
final String requestMsg = desp.replaceFirst("^" + title + "(.*)", "").trim();
Log.i(TAG, "requestMsg:" + requestMsg);
OkHttpClient client = new OkHttpClient().newBuilder().build();
MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM)
OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();
//设置重试拦截器
if (retryInterceptor != null) clientBuilder.addInterceptor(retryInterceptor);
//设置读取超时时间
OkHttpClient client = clientBuilder
.readTimeout(Define.REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS)
.writeTimeout(Define.REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS)
.connectTimeout(Define.REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS)
.build();
MultipartBody.Builder bodyBuilder = new MultipartBody.Builder().setType(MultipartBody.FORM)
.addFormDataPart("title", title)
.addFormDataPart("desp", requestMsg);
RequestBody body = builder.build();
RequestBody body = bodyBuilder.build();
Request request = new Request.Builder().url(requestUrl).method("POST", body).build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(@NonNull Call call, @NonNull final IOException e) {
LogUtil.updateLog(logId, 0, e.getMessage());
Toast(handError, TAG, "发送失败:" + e.getMessage());
if (emitter != null) emitter.onError(new Exception("RxJava 请求接口异常..."));
}
@Override
public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
final String responseStr = Objects.requireNonNull(response.body()).string();
Log.d(TAG, "Response" + response.code() + "" + responseStr);
Toast(handError, TAG, "发送状态:" + responseStr);
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
//TODO:粗略解析是否发送成功
if (responseStr.contains("\"code\":0")) {
LogUtil.updateLog(logId, 2, responseStr);
} else {
LogUtil.updateLog(logId, 0, responseStr);
}
final String responseStr = Objects.requireNonNull(response.body()).string();
Log.d(TAG, "Response" + response.code() + "" + responseStr);
Toast(handError, TAG, "发送状态:" + responseStr);
//TODO:粗略解析是否发送成功
if (responseStr.contains("\"code\":0")) {
LogUtil.updateLog(logId, 2, responseStr);
} else {
LogUtil.updateLog(logId, 0, responseStr);
}
});
}
}

View File

@ -4,10 +4,9 @@ import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import androidx.annotation.NonNull;
import com.alibaba.fastjson.JSON;
import com.idormy.sms.forwarder.model.vo.TelegramSettingVo;
import com.idormy.sms.forwarder.utils.Define;
import com.idormy.sms.forwarder.utils.LogUtil;
import java.io.IOException;
@ -18,11 +17,6 @@ import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import io.reactivex.rxjava3.core.ObservableEmitter;
import okhttp3.Authenticator;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.ConnectionPool;
import okhttp3.Credentials;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
@ -35,7 +29,7 @@ public class SenderTelegramMsg extends SenderBaseMsg {
static final String TAG = "SenderTelegramMsg";
public static void sendMsg(final long logId, final Handler handError, final ObservableEmitter<Object> emitter, TelegramSettingVo telegramSettingVo, final String from, final String text, final String method) throws Exception {
public static void sendMsg(final long logId, final Handler handError, final RetryIntercepter retryInterceptor, TelegramSettingVo telegramSettingVo, final String from, final String text, final String method) throws Exception {
Log.i(TAG, "sendMsg telegramSettingVo:" + telegramSettingVo.toString() + " text:" + text);
String apiToken = telegramSettingVo.getApiToken();
@ -62,88 +56,67 @@ public class SenderTelegramMsg extends SenderBaseMsg {
final String proxyUsername = telegramSettingVo.getProxyUsername();
final String proxyPassword = telegramSettingVo.getProxyPassword();
try {
Proxy proxy = null;
Authenticator proxyAuthenticator = null;
OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();
//设置代理
if ((proxyType == Proxy.Type.HTTP || proxyType == Proxy.Type.SOCKS) && !TextUtils.isEmpty(proxyHost) && !TextUtils.isEmpty(proxyPort)) {
//代理服务器的IP和端口号
clientBuilder.proxy(new Proxy(proxyType, new InetSocketAddress(proxyHost, Integer.parseInt(proxyPort))));
if ((proxyType == Proxy.Type.HTTP || proxyType == Proxy.Type.SOCKS) && !TextUtils.isEmpty(proxyHost) && !TextUtils.isEmpty(proxyPort)) {
proxy = new Proxy(proxyType, new InetSocketAddress(proxyHost, Integer.parseInt(proxyPort)));
if (needProxyAuthenticator && (!TextUtils.isEmpty(proxyUsername) || !TextUtils.isEmpty(proxyPassword))) {
proxyAuthenticator = (route, response) -> {
String credential = Credentials.basic("jesse", "password1");
return response.request().newBuilder()
.header("Authorization", credential)
.build();
};
}
//代理的鉴权账号密码
if (needProxyAuthenticator && (!TextUtils.isEmpty(proxyUsername) || !TextUtils.isEmpty(proxyPassword))) {
clientBuilder.proxyAuthenticator((route, response) -> {
//设置代理服务器账号密码
String credential = Credentials.basic(proxyUsername, proxyPassword);
return response.request().newBuilder()
.header("Proxy-Authorization", credential)
.build();
});
}
}
//设置重试拦截器
if (retryInterceptor != null) clientBuilder.addInterceptor(retryInterceptor);
//设置读取超时时间
OkHttpClient client = clientBuilder
.readTimeout(Define.REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS)
.writeTimeout(Define.REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS)
.connectTimeout(Define.REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS)
.build();
OkHttpClient client;
if (proxy != null && proxyAuthenticator != null) {
client = new OkHttpClient().newBuilder().proxy(proxy).proxyAuthenticator(proxyAuthenticator)
.connectTimeout(120, TimeUnit.SECONDS).readTimeout(120, TimeUnit.SECONDS)
.connectionPool(new ConnectionPool(5, 1, TimeUnit.SECONDS)).build();
} else if (proxy != null) {
client = new OkHttpClient().newBuilder().proxy(proxy)
.connectTimeout(120, TimeUnit.SECONDS).readTimeout(120, TimeUnit.SECONDS)
.connectionPool(new ConnectionPool(5, 1, TimeUnit.SECONDS)).build();
final Request request;
if (method.equals("GET")) {
request = new Request.Builder()
.url(requestUrl + "?chat_id=" + chatId + "&text=" + finalText)
.build();
} else {
Map bodyMap = new HashMap();
bodyMap.put("chat_id", chatId);
bodyMap.put("text", finalText);
bodyMap.put("parse_mode", "HTML");
String requestMsg = JSON.toJSONString(bodyMap);
Log.i(TAG, "requestMsg:" + requestMsg);
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), requestMsg);
request = new Request.Builder()
.url(requestUrl)
.addHeader("Content-Type", "application/json; charset=utf-8")
.post(requestBody)
.build();
}
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
final String responseStr = Objects.requireNonNull(response.body()).string();
Log.d(TAG, "Response" + response.code() + "" + responseStr);
Toast(handError, TAG, "发送状态:" + responseStr);
//TODO:粗略解析是否发送成功
if (responseStr.contains("\"ok\":true")) {
LogUtil.updateLog(logId, 2, responseStr);
} else {
client = new OkHttpClient().newBuilder()
.connectTimeout(120, TimeUnit.SECONDS).readTimeout(120, TimeUnit.SECONDS)
.connectionPool(new ConnectionPool(5, 1, TimeUnit.SECONDS)).build();
LogUtil.updateLog(logId, 0, responseStr);
}
final Request request;
if (method.equals("GET")) {
request = new Request.Builder()
.url(requestUrl + "?chat_id=" + chatId + "&text=" + finalText)
.build();
} else {
Map bodyMap = new HashMap();
bodyMap.put("chat_id", chatId);
bodyMap.put("text", finalText);
bodyMap.put("parse_mode", "HTML");
String requestMsg = JSON.toJSONString(bodyMap);
Log.i(TAG, "requestMsg:" + requestMsg);
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), requestMsg);
request = new Request.Builder()
.url(requestUrl)
.addHeader("Content-Type", "application/json; charset=utf-8")
.post(requestBody)
.build();
}
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(@NonNull Call call, @NonNull final IOException e) {
LogUtil.updateLog(logId, 0, e.getMessage());
Toast(handError, TAG, "发送失败:" + e.getMessage());
if (emitter != null) emitter.onError(new Exception("RxJava 请求接口异常..."));
}
@Override
public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
final String responseStr = Objects.requireNonNull(response.body()).string();
Log.d(TAG, "Response" + response.code() + "" + responseStr);
Toast(handError, TAG, "发送状态:" + responseStr);
//TODO:粗略解析是否发送成功
if (responseStr.contains("\"ok\":true")) {
LogUtil.updateLog(logId, 2, responseStr);
} else {
LogUtil.updateLog(logId, 0, responseStr);
}
}
});
} catch (Exception e) {
LogUtil.updateLog(logId, 0, e.getMessage());
Log.e(TAG, e.getMessage(), e);
Toast(handError, TAG, "发送失败:" + e.getMessage());
if (emitter != null) emitter.onError(new Exception("RxJava 请求接口异常..."));
}
}

View File

@ -4,22 +4,19 @@ import android.os.Handler;
import android.util.Base64;
import android.util.Log;
import androidx.annotation.NonNull;
import com.idormy.sms.forwarder.utils.CertUtils;
import com.idormy.sms.forwarder.utils.Define;
import com.idormy.sms.forwarder.utils.LogUtil;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import io.reactivex.rxjava3.core.ObservableEmitter;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
@ -32,7 +29,7 @@ public class SenderWebNotifyMsg extends SenderBaseMsg {
static final String TAG = "SenderWebNotifyMsg";
public static void sendMsg(final long logId, final Handler handError, final ObservableEmitter<Object> emitter, String webServer, String webParams, String secret, String method, String from, String content) throws Exception {
public static void sendMsg(final long logId, final Handler handError, final RetryIntercepter retryInterceptor, String webServer, String webParams, String secret, String method, String from, String content) throws Exception {
Log.i(TAG, "sendMsg webServer:" + webServer + " webParams:" + webParams + " from:" + from + " content:" + content);
if (webServer == null || webServer.isEmpty()) {
@ -92,34 +89,32 @@ public class SenderWebNotifyMsg extends SenderBaseMsg {
request = new Request.Builder().url(webServer).method("POST", body).build();
}
OkHttpClient client = new OkHttpClient().newBuilder()
//忽略https证书
.sslSocketFactory(CertUtils.getSSLSocketFactory(), CertUtils.getX509TrustManager())
.hostnameVerifier(CertUtils.getHostnameVerifier())
OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();
//设置重试拦截器
if (retryInterceptor != null) clientBuilder.addInterceptor(retryInterceptor);
//忽略https证书
clientBuilder.sslSocketFactory(CertUtils.getSSLSocketFactory(), CertUtils.getX509TrustManager()).hostnameVerifier(CertUtils.getHostnameVerifier());
//设置读取超时时间
OkHttpClient client = clientBuilder
.readTimeout(Define.REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS)
.writeTimeout(Define.REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS)
.connectTimeout(Define.REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(@NonNull Call call, @NonNull final IOException e) {
LogUtil.updateLog(logId, 0, e.getMessage());
Toast(handError, TAG, "发送失败:" + e.getMessage());
if (emitter != null) emitter.onError(new Exception("RxJava 请求接口异常..."));
}
@Override
public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
final String responseStr = Objects.requireNonNull(response.body()).string();
Log.d(TAG, "Response" + response.code() + "" + responseStr);
Toast(handError, TAG, "发送状态:" + responseStr);
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
//返回http状态200即为成功
if (200 == response.code()) {
LogUtil.updateLog(logId, 2, responseStr);
} else {
LogUtil.updateLog(logId, 0, responseStr);
}
final String responseStr = Objects.requireNonNull(response.body()).string();
Log.d(TAG, "Response" + response.code() + "" + responseStr);
Toast(handError, TAG, "发送状态:" + responseStr);
//返回http状态200即为成功
if (response.isSuccessful()) {
LogUtil.updateLog(logId, 2, responseStr);
} else {
LogUtil.updateLog(logId, 0, responseStr);
}
});
}
}

View File

@ -32,4 +32,7 @@ public class Define {
public static final String SP_MSG = "forwarder_msg";
public static final String SP_MSG_SET_KEY = "forwarder_msg_set_key";
//OkHttp 请求超时时间
public static final int REQUEST_TIMEOUT_SECONDS = 5;
}

View File

@ -88,11 +88,13 @@ public class LogUtil {
public static void updateLog(Long id, int forward_status, String forward_response) {
if (id == null || id <= 0) return;
if (forward_response == null) forward_response = "";
@SuppressWarnings("StringBufferReplaceableByString") String sql = new StringBuilder().append("UPDATE ").append(LogTable.LogEntry.TABLE_NAME)
.append(" SET ").append(LogTable.LogEntry.COLUMN_NAME_FORWARD_STATUS).append(" = ? , ")
.append(LogTable.LogEntry.COLUMN_NAME_FORWARD_RESPONSE)
.append(" = CASE WHEN ").append(LogTable.LogEntry.COLUMN_NAME_FORWARD_STATUS).append(" = 1 THEN ? ELSE ")
.append(" = CASE WHEN (trim(").append(LogTable.LogEntry.COLUMN_NAME_FORWARD_RESPONSE)
.append(") = '' or trim(").append(LogTable.LogEntry.COLUMN_NAME_FORWARD_RESPONSE).append(") = 'ok') THEN ? ELSE ")
.append(LogTable.LogEntry.COLUMN_NAME_FORWARD_RESPONSE).append(" || '\n ---------- \n' || ? END ")
.append(" WHERE ").append(LogTable.LogEntry._ID).append(" = ? ")
.toString();

View File

@ -36,7 +36,7 @@
<ImageView
android:id="@+id/ivStep_12_1"
android:layout_width="15dp"
android:layout_height="4dp"
android:layout_height="2dp"
android:layout_gravity="center"
android:src="@drawable/step_rectangle_normal"
tools:ignore="ContentDescription" />
@ -44,7 +44,7 @@
<ImageView
android:id="@+id/ivStep_12_2"
android:layout_width="0dp"
android:layout_height="4dp"
android:layout_height="2dp"
android:layout_weight="1"
android:src="@drawable/step_rectangle_normal"
tools:ignore="ContentDescription" />
@ -52,7 +52,7 @@
<ImageView
android:id="@+id/ivStep_12_3"
android:layout_width="15dp"
android:layout_height="4dp"
android:layout_height="2dp"
android:layout_gravity="center"
android:src="@drawable/step_rectangle_normal"
tools:ignore="ContentDescription" />
@ -70,7 +70,7 @@
<ImageView
android:id="@+id/ivStep_23_1"
android:layout_width="15dp"
android:layout_height="4dp"
android:layout_height="2dp"
android:layout_gravity="center"
android:src="@drawable/step_rectangle_normal"
tools:ignore="ContentDescription" />
@ -78,7 +78,7 @@
<ImageView
android:id="@+id/ivStep_23_2"
android:layout_width="0dp"
android:layout_height="4dp"
android:layout_height="2dp"
android:layout_weight="1"
android:src="@drawable/step_rectangle_normal"
tools:ignore="ContentDescription" />
@ -86,7 +86,7 @@
<ImageView
android:id="@+id/ivStep_23_3"
android:layout_width="15dp"
android:layout_height="4dp"
android:layout_height="2dp"
android:layout_gravity="center"
android:src="@drawable/step_rectangle_normal"
tools:ignore="ContentDescription" />
@ -104,7 +104,7 @@
<ImageView
android:id="@+id/ivStep_34_1"
android:layout_width="15dp"
android:layout_height="4dp"
android:layout_height="2dp"
android:layout_gravity="center"
android:src="@drawable/step_rectangle_normal"
tools:ignore="ContentDescription" />
@ -112,7 +112,7 @@
<ImageView
android:id="@+id/ivStep_34_2"
android:layout_width="0dp"
android:layout_height="4dp"
android:layout_height="2dp"
android:layout_weight="1"
android:src="@drawable/step_rectangle_normal"
tools:ignore="ContentDescription" />
@ -121,7 +121,7 @@
<ImageView
android:id="@+id/ivStep_34_3"
android:layout_width="15dp"
android:layout_height="4dp"
android:layout_height="2dp"
android:layout_gravity="center"
android:src="@drawable/step_rectangle_normal"
tools:ignore="ContentDescription" />

View File

@ -174,11 +174,11 @@
<string name="retry_interval">请求接口失败重试</string>
<string name="retry_interval_tips">次数=0时禁用间隔逐次递增</string>
<string name="forward_sms">转发短信广播</string>
<string name="forward_sms_tips">总开关,请授予读取短信、通知类短信、发送短信等权限</string>
<string name="forward_sms_tips">授予读取短信、通知类短信、发送短信等权限,关闭验证码保护</string>
<string name="forward_missed_calls">转发通话记录</string>
<string name="forward_missed_calls_tips">请先授予读取通话记录、联系人等权限,并选择转发类型,再开启</string>
<string name="forward_app_notify">转发应用通知</string>
<string name="forward_app_notify_tips">请先授予通知使用权,再开启;开启自动消除,以避免多条通知堆叠</string>
<string name="forward_app_notify_tips">请先授予通知使用权,再开启;开启“自动消除”可避免多条通知堆叠</string>
<string name="cancel_app_notify">自动消除通知</string>
<string name="enable_custom_templates">启用自定义模版</string>
<string name="enable_custom_templates_tips">优先级:转发规则的自定义模板 > 全局自定义模版 > 默认</string>