保誠-保戶業務員媒合平台
wayne
2022-02-17 a3716f72066d25d745f4d5103ff23a553c3e102b
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
package com.pollex.pam.service;
 
import com.fasterxml.jackson.databind.ObjectMapper;
import com.pollex.pam.config.ApplicationProperties;
import com.pollex.pam.config.ApplicationProperties.Email;
import com.pollex.pam.config.ApplicationProperties.SMS;
import com.pollex.pam.config.Constants;
import com.pollex.pam.enums.SendEmailMsgMethod;
import com.pollex.pam.repository.ConsultantRepository;
import com.pollex.pam.service.dto.*;
import com.pollex.pam.service.util.HttpRequestUtil;
import com.pollex.pam.web.rest.errors.SendEmailFailException;
import com.pollex.pam.web.rest.errors.SendSMSFailException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.core.env.Profiles;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.thymeleaf.spring5.SpringTemplateEngine;
import tech.jhipster.config.JHipsterConstants;
 
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.Base64.Encoder;
 
@Service
public class SendMsgService {
 
    private static final Logger log = LoggerFactory.getLogger(SendMsgService.class);
    private final Encoder encoder = Base64.getEncoder();
 
    private static final String SEND_SMS_SUCCESS_CODE = "1";
 
    @Autowired
    ApplicationProperties applicationProperties;
 
    @Autowired
    ConsultantRepository consultantRepository;
 
    @Autowired
    SpringTemplateEngine springTemplateEngine;
 
    @Autowired
    Environment environment;
 
    @Autowired
    MailService mailService;
 
    public SendSMSResponse sendMsgBySMS(String toMobile, String content) throws SendSMSFailException {
 
        SMS smsProperties = applicationProperties.getSms();
        if(!smsProperties.isSendNotifyMsg()) {
//            return getMockSMSResponse();
            return null;
        }
 
        SendSMSRequest sendSMSRequest = new SendSMSRequest();
        sendSMSRequest.setpKey(UUID.randomUUID().toString());
        sendSMSRequest.setSourceCode(smsProperties.getSourceCode());
        sendSMSRequest.setSender(smsProperties.getSender());
        sendSMSRequest.setMsgTypeSet(smsProperties.getSmsType());
        sendSMSRequest.setSendTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:00")));
        sendSMSRequest.setSubject(encoder.encodeToString(smsProperties.getSubject().getBytes(StandardCharsets.UTF_8)));
        sendSMSRequest.setActivityId("");
 
        SMSDetail smsDetail = new SMSDetail();
        smsDetail.setMobile(toMobile);
        smsDetail.setContent(encoder.encodeToString(content.getBytes(StandardCharsets.UTF_8)));
 
        sendSMSRequest.setDetail(Collections.singletonList(smsDetail));
 
        try {
            ResponseEntity<SendSMSResponse> responseEntity = HttpRequestUtil.postWithJson(smsProperties.getUrl(), sendSMSRequest, SendSMSResponse.class);
            SendSMSResponse response = responseEntity.getBody();
 
            log.debug("response status code = {}", responseEntity.getStatusCode());
            log.debug("smsResponse = {}", responseEntity.getBody());
 
            if(!SEND_SMS_SUCCESS_CODE.equals(response.getReturnCode())) {
                throw new SendSMSFailException("sms service return code = " + response.getReturnCode() + ", error_msg = " + response.getErrorMsg());
            }
 
            return responseEntity.getBody();
        } catch (SendSMSFailException e) {
            throw e;
        } catch (Exception e) {
            log.warn("send sms fail by other reason!", e);
            throw new SendSMSFailException("send sms fail by other reason!");
        }
    }
 
//    private SendSMSResponse getMockSMSResponse() {
//        SendSMSResponse mock = new SendSMSResponse();
//        mock.set
//        return null;
//    }
 
    public String sendMsgByEmail(String to, String subject, String content, boolean htmlFormat) throws SendEmailFailException{
        return sendMsgByEmail(to, subject, content, htmlFormat, Collections.emptyList(), Collections.emptyList());
    }
 
    public String sendMsgByEmail(String toAddress, String subject, String content, boolean htmlFormat, List<String> toCCAddress,
        List<String> attachments) throws SendEmailFailException {
        String fromAddress = applicationProperties.getEmail().getSenderEmail();
 
        SendMailRequest sendMailRequest = new SendMailRequest();
        sendMailRequest.setSendMailAddresses(Collections.singletonList(toAddress));
        sendMailRequest.setFrom(fromAddress);
        sendMailRequest.setContent(content);
        sendMailRequest.setSubject(subject);
        sendMailRequest.setSendCCMailAddresses(toCCAddress);
        sendMailRequest.setAttachments(attachments);
        sendMailRequest.setHtmlFormat(htmlFormat);
        sendMailRequest.setFunctionId(applicationProperties.getEmail().getFunctionId());
 
        return sendMsgByEmail(sendMailRequest);
    }
 
    public String sendMsgByEmail(SendMailRequest sendMailRequest) throws SendEmailFailException{
        final Email emailProperties = applicationProperties.getEmail();
 
        if(!emailProperties.isSendNotifyMsg()) {
            return null;
        }
 
        if(emailProperties.getMethod() == SendEmailMsgMethod.POLLEX_GMAIL) {
            return sendMsgByPollexGmail(sendMailRequest);
        }
        else if(emailProperties.getMethod() == SendEmailMsgMethod.PAM_EMAIL_SERVICE) {
            return sendMsgByPamEmailService(sendMailRequest);
        }
 
        return null;
    }
 
    private String sendMsgByPollexGmail(SendMailRequest sendMailRequest) {
        String subject = sendMailRequest.getSubject();
        String content = sendMailRequest.getContent();
        boolean isHtml = sendMailRequest.isHtmlFormat();
        sendMailRequest.getSendMailAddresses().forEach(receiver -> mailService.sendEmail(receiver, subject, content, false, isHtml));
 
        return null;
    }
 
    private String sendMsgByPamEmailService(SendMailRequest sendMailRequest) {
        final Email emailProperties = applicationProperties.getEmail();
        try {
            ResponseEntity<String> responseEntity =
                HttpRequestUtil.postWithJson(emailProperties.getUrl(), sendMailRequest, String.class);
            log.debug("responseEntity = {}", responseEntity);
 
            String rawResponseString = responseEntity.getBody();
            SendMailResponse sendMailResponse = new ObjectMapper().readValue(rawResponseString, SendMailResponse.class);
            log.debug("sendMailResponse = {}", sendMailResponse);
 
            if (sendMailResponse == null || sendMailResponse.getData() == null || !"ADDED".equalsIgnoreCase(sendMailResponse.getData().getMessageStatus())) {
                throw new SendEmailFailException("send email service return error msg! raw response string= " + rawResponseString);
            }
 
            return responseEntity.getBody();
        } catch (SendEmailFailException e) {
            throw e;
        } catch (Exception e) {
            log.warn("send email fail by other reason", e);
            throw new SendEmailFailException("send email failed!");
        }
    }
}