admin
2022-01-12 4a7367a869ef12375ea6678ca44e102b8919c624
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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
package cn.jpush.api.report;
 
 
import cn.jiguang.common.ClientConfig;
import cn.jiguang.common.ServiceHelper;
import cn.jiguang.common.TimeUnit;
import cn.jiguang.common.connection.HttpProxy;
import cn.jiguang.common.connection.NativeHttpClient;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jiguang.common.resp.BaseResult;
import cn.jiguang.common.resp.ResponseWrapper;
import cn.jiguang.common.utils.StringUtils;
import cn.jpush.api.report.model.CheckMessagePayload;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
 
import java.lang.reflect.Type;
import java.net.URLEncoder;
import java.util.Map;
import java.util.regex.Pattern;
 
public class ReportClient {    
 
    private final NativeHttpClient _httpClient;
    private String _hostName;
    private String _receivePath;
    private String _userPath;
    private String _messagePath;
    private String _statusPath;
 
    private String messageDetailPath;
    private String receiveDetailPath;
    private String groupMessageDetailPath;
    private String groupUserPath;
 
    public ReportClient(String masterSecret, String appKey) {
        this(masterSecret, appKey, null, ClientConfig.getInstance());
    }
 
    /**
     * This will be removed in the future. Please use ClientConfig{jiguang-common cn.jiguang.common.ClientConfig#setMaxRetryTimes} instead of this constructor.
     * @param masterSecret  API access secret of the appKey.
     * @param appKey The KEY of one application on JPush.
     * @param maxRetryTimes max retry times.
     *
     */
    @Deprecated
    public ReportClient(String masterSecret, String appKey, int maxRetryTimes) {
        this(masterSecret, appKey, maxRetryTimes, null);
    }
 
    /**
     * This will be removed in the future. Please use ClientConfig{jiguang-common cn.jiguang.common.ClientConfig#setMaxRetryTimes} instead of this constructor.
     * @param masterSecret  API access secret of the appKey.
     * @param appKey The KEY of one application on JPush.
     * @param maxRetryTimes max retry times
     * @param proxy The max retry times.
     *
     */
    @Deprecated
    public ReportClient(String masterSecret, String appKey, int maxRetryTimes, HttpProxy proxy) {
        ServiceHelper.checkBasic(appKey, masterSecret);
 
        ClientConfig conf = ClientConfig.getInstance();
        conf.setMaxRetryTimes(maxRetryTimes);
 
        _hostName = (String) conf.get(ClientConfig.REPORT_HOST_NAME);
        _receivePath = (String) conf.get(ClientConfig.REPORT_RECEIVE_PATH);
        _userPath = (String) conf.get(ClientConfig.REPORT_USER_PATH);
        _messagePath = (String) conf.get(ClientConfig.REPORT_MESSAGE_PATH);
        _statusPath = (String) conf.get(ClientConfig.REPORT_STATUS_PATH);
 
        messageDetailPath = (String) conf.get(ClientConfig.REPORT_MESSAGE_DETAIL_PATH);
        receiveDetailPath = (String) conf.get(ClientConfig.REPORT_RECEIVE_DETAIL_PATH);
        groupMessageDetailPath = (String) conf.get(ClientConfig.REPORT_GROUP_MESSAGE_DETAIL_PATH);
        groupUserPath = (String) conf.get(ClientConfig.REPORT_GROUP_USER_PATH);
 
        String authCode = ServiceHelper.getBasicAuthorization(appKey, masterSecret);
        _httpClient = new NativeHttpClient(authCode, proxy, conf);
    }
 
    public ReportClient(String masterSecret, String appKey, HttpProxy proxy, ClientConfig conf) {
        ServiceHelper.checkBasic(appKey, masterSecret);
 
        _hostName = (String) conf.get(ClientConfig.REPORT_HOST_NAME);
        _receivePath = (String) conf.get(ClientConfig.REPORT_RECEIVE_PATH);
        _userPath = (String) conf.get(ClientConfig.REPORT_USER_PATH);
        _messagePath = (String) conf.get(ClientConfig.REPORT_MESSAGE_PATH);
        _statusPath = (String) conf.get(ClientConfig.REPORT_STATUS_PATH);
 
        messageDetailPath = (String) conf.get(ClientConfig.REPORT_MESSAGE_DETAIL_PATH);
        receiveDetailPath = (String) conf.get(ClientConfig.REPORT_RECEIVE_DETAIL_PATH);
        groupMessageDetailPath = (String) conf.get(ClientConfig.REPORT_GROUP_MESSAGE_DETAIL_PATH);
        groupUserPath = (String) conf.get(ClientConfig.REPORT_GROUP_USER_PATH);
 
        String authCode = ServiceHelper.getBasicAuthorization(appKey, masterSecret);
        _httpClient = new NativeHttpClient(authCode, proxy, conf);
    }
    
    
    public ReceivedsResult getReceiveds(String[] msgIdArray) 
            throws APIConnectionException, APIRequestException {
        return getReceiveds(StringUtils.arrayToString(msgIdArray));
    }
    
    public ReceivedsResult getReceiveds(String msgIds) 
            throws APIConnectionException, APIRequestException {
        checkMsgids(msgIds);
        
        String url = _hostName + _receivePath + "?msg_ids=" + msgIds;
        ResponseWrapper response = _httpClient.sendGet(url);
        
        return ReceivedsResult.fromResponse(response);
    }
 
    public ReceivedsResult getReceivedsDetail(String msgIds)
            throws APIConnectionException, APIRequestException {
        checkMsgids(msgIds);
 
        String url = _hostName + receiveDetailPath + "?msg_ids=" + msgIds;
        ResponseWrapper response = _httpClient.sendGet(url);
 
        return ReceivedsResult.fromResponse(response);
    }
    
    public MessagesResult getMessages(String msgIds) 
            throws APIConnectionException, APIRequestException {
        checkMsgids(msgIds);
        
        String url = _hostName + _messagePath + "?msg_ids=" + msgIds;
        ResponseWrapper response = _httpClient.sendGet(url);
        
        return MessagesResult.fromResponse(response);
    }
 
    public MessageDetailResult getMessagesDetail(String msgIds)
            throws APIConnectionException, APIRequestException {
        checkMsgids(msgIds);
 
        String url = _hostName + messageDetailPath + "?msg_ids=" + msgIds;
        ResponseWrapper response = _httpClient.sendGet(url);
 
        return MessageDetailResult.fromResponse(response);
    }
 
 
    public GroupMessageDetailResult getGroupMessagesDetail(String groupMsgIds)
            throws APIConnectionException, APIRequestException {
        String url = _hostName + groupMessageDetailPath + "?group_msgids=" + groupMsgIds;
        ResponseWrapper response = _httpClient.sendGet(url);
 
        return GroupMessageDetailResult.fromResponse(response);
    }
 
 
    public Map<String, MessageStatus> getMessagesStatus(CheckMessagePayload payload)
            throws APIConnectionException, APIRequestException {
        String url = _hostName + (_statusPath.endsWith("/message")?_statusPath:(_statusPath+"/message"));
        ResponseWrapper result = _httpClient.sendPost(url, payload.toString());
        Type type = new TypeToken<Map<String, MessageStatus>>(){}.getType();
        return new Gson().fromJson(result.responseContent, type);
    }
    
    public UsersResult getUsers(TimeUnit timeUnit, String start, int duration) 
            throws APIConnectionException, APIRequestException {        
        String startEncoded = null;
        try {
            startEncoded = URLEncoder.encode(start, "utf-8");
        } catch (Exception e) {
        }
        
        String url = _hostName + _userPath
                + "?time_unit=" + timeUnit.toString()
                + "&start=" + startEncoded + "&duration=" + duration;
        ResponseWrapper response = _httpClient.sendGet(url);
        
        return BaseResult.fromResponse(response, UsersResult.class);
    }
 
    public GroupUsersResult getGroupUsers(TimeUnit timeUnit, String start, int duration)
            throws APIConnectionException, APIRequestException {
        String startEncoded = null;
        try {
            startEncoded = URLEncoder.encode(start, "utf-8");
        } catch (Exception e) {
        }
 
        String url = _hostName + groupUserPath
                + "?time_unit=" + timeUnit.toString()
                + "&start=" + startEncoded + "&duration=" + duration;
        ResponseWrapper response = _httpClient.sendGet(url);
 
        return BaseResult.fromResponse(response, GroupUsersResult.class);
    }
 
    
    private final static Pattern MSGID_PATTERNS = Pattern.compile("[^0-9, ]");
 
    public static void checkMsgids(String msgIds) {
        if (StringUtils.isTrimedEmpty(msgIds)) {
            throw new IllegalArgumentException("msgIds param is required.");
        }
        
        if (MSGID_PATTERNS.matcher(msgIds).find()) {
            throw new IllegalArgumentException("msgIds param format is incorrect. "
                    + "It should be msg_id (number) which response from JPush Push API. "
                    + "If there are many, use ',' as interval. ");
        }
        
        msgIds = msgIds.trim();
        if (msgIds.endsWith(",")) {
            msgIds = msgIds.substring(0, msgIds.length() - 1);
        }
        
        String[] splits = msgIds.split(",");
        try {
            for (String s : splits) {
                s = s.trim();
                if (!StringUtils.isEmpty(s)) {
                    Long.parseLong(s);
                }
            }
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("Every msg_id should be valid Long number which splits by ','");
        }
    }
 
}