shikeying
2024-01-11 3b67e947e36133e2a40eb2737b15ea375e157ea0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
package com.walker.push.alidy;
 
import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.walker.infrastructure.utils.JsonUtils;
import com.walker.infrastructure.utils.StringUtils;
import com.walker.push.Notification;
import com.walker.push.PushException;
import com.walker.push.PushResult;
import com.walker.push.SmsMessage;
import com.walker.push.support.AbstractSmsPush;
import com.walker.push.util.PushUtils;
import darabonba.core.client.ClientOverrideConfiguration;
 
import java.util.List;
import java.util.concurrent.CompletableFuture;
 
/**
 * 阿里大鱼短信推送实现。
 * @author 时克英
 * @date 2023-04-23
 */
public abstract class DySmsPush extends AbstractSmsPush {
 
    public DySmsPush(){
        this.setId("alidy_sms_push");
        this.setName("大鱼短信推送");
        this.setSupportAsync(true);
    }
 
    @Override
    public void startup() {
        if(StringUtils.isEmpty(this.accessKeyId)
                || StringUtils.isEmpty(this.accessKeySecret)
                || StringUtils.isEmpty(this.signName)
                || StringUtils.isEmpty(this.region)){
            throw new IllegalArgumentException("请先设置短信配置:" + this.getName());
        }
 
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId(this.accessKeyId)
                .accessKeySecret(this.accessKeySecret)
                //.securityToken("<your-token>") // use STS token
                .build());
 
        client = AsyncClient.builder()
                .region(this.region) // Region ID
                //.httpClient(httpClient) // Use the configured HttpClient, otherwise use the default HttpClient (Apache HttpClient)
                .credentialsProvider(provider)
                //.serviceConfiguration(Configuration.create()) // Service-level configuration
                // Client-level configuration rewrite, can set Endpoint, Http request parameters, etc.
                .overrideConfiguration(
                        ClientOverrideConfiguration.create().setEndpointOverride("dysmsapi.aliyuncs.com")
                        //.setConnectTimeout(Duration.ofSeconds(30))
                )
                .build();
        logger.info("初始化:大鱼短信推送者");
    }
 
    @Override
    protected PushResult doPushContent(Notification notification, List<SmsMessage> data) throws PushException {
        if(notification.getBroadcast()){
            throw new IllegalStateException("短信推送,无法设置为广播!");
        }
 
        PushResult pushResult = PushUtils.acquireSuccessPushResult();
 
        // 对于短信来说,通常一个提醒只会通知一人,不会群发同一个信息给多人。
        // 因为一个:SmsMessage 中就能放多个手机号,所以其实只有一个对象。
        SmsMessage smsMessage = data.get(0);
 
        String phoneNumbers = StringUtils.collectionToDelimitedString(smsMessage.getMobileList(), StringUtils.DEFAULT_SPLIT_SEPARATOR);
        String templateParam = null;
        try {
            templateParam = JsonUtils.objectToJsonString(smsMessage.getTemplateParam());
//            int i = 0;
//            StringBuilder sb = new StringBuilder("{");
//            for(Map.Entry<String, String> entry: smsMessage.getTemplateParam().entrySet()){
//                if(i > 0){
//                    sb.append(",");
//                }
//                sb.append("\"").append(entry.getKey()).append("\"");
//                sb.append(":");
//                sb.append("\"").append(entry.getValue()).append("\"");
//                i++;
//            }
//            sb.append("}");
//            templateParam = sb.toString();
//            System.out.println(templateParam);
        } catch (Exception e) {
            throw new PushException(notification.getId(), "短信json转换错误:" + e.getMessage(), e);
        }
 
        SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                .phoneNumbers(phoneNumbers)
                .signName(this.signName)
                .templateCode(smsMessage.getTemplateId()).templateParam(templateParam)
                .build();
 
//        CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
        // 当执行发送完成时,使用发送任务的线程继续执行:回调任务
        CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest).whenComplete((res, ex) -> {
            if(ex != null){
                this.getPushStatusListener().onException(notification, ex.getMessage(), this.getNotificationChannel());
            } else {
                this.getPushStatusListener().onSuccess(notification, res.getBody().getBizId(), this.getNotificationChannel());
            }
        });
 
        try {
            // 2023-04-24, 注意:这里get必须调用,否则无法触发远程通信!
            response.get();
        } catch (Exception e) {
            throw new PushException(notification.getId(), e.getMessage(), e);
        }
//        SendSmsResponse resp = response.get();
        return pushResult;
    }
 
//    @Override
//    public NotificationChannel getNotificationChannel() {
//        return NotificationChannel.Sms;
//    }
 
//    @Override
//    public List<SmsMessage> translateToTarget(Notification notification) {
//        List<SmsMessage> data = new ArrayList<>(4);
//        SmsMessage smsMessage = new SmsMessage();
//        String userPhoneNum = null;
//        for(String user: notification.getReceiverList()){
//            userPhoneNum = this.getUserMobile(user);
//            if(StringUtils.isEmpty(userPhoneNum)){
//                logger.warn("未查找到用户手机号,user = {}", user);
//                continue;
//            }
//            smsMessage.addMobile(userPhoneNum);
//        }
//
//        try {
//            SmsMessage message = JsonUtils.jsonStringToObject(notification.getContent(), SmsMessage.class);
//            smsMessage.setTemplateId(message.getTemplateId());
//            smsMessage.setTemplateParam(message.getTemplateParam());
//        } catch (Exception e) {
//            throw new RuntimeException("消息内容json转换错误:" + e.getMessage(), e);
//        }
//        data.add(smsMessage);
//        return data;
//    }
 
    public String getAccessKeyId() {
        return accessKeyId;
    }
 
    public void setAccessKeyId(String accessKeyId) {
        this.accessKeyId = accessKeyId;
    }
 
    public String getAccessKeySecret() {
        return accessKeySecret;
    }
 
    public void setAccessKeySecret(String accessKeySecret) {
        this.accessKeySecret = accessKeySecret;
    }
 
    public String getSignName() {
        return signName;
    }
 
    public void setSignName(String signName) {
        this.signName = signName;
    }
 
    public String getRegion() {
        return region;
    }
 
    public void setRegion(String region) {
        this.region = region;
    }
 
    private AsyncClient client = null;
    private String accessKeyId;
    private String accessKeySecret;
    private String signName;
    private String region;
}