admin
2020-05-19 744594ef1a2f530fc3e86ea9dc48b62247f79420
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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
package com.yeshi.fanli.util.push;
 
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
 
import javax.annotation.PostConstruct;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.yeshi.utils.HttpUtil;
 
import com.google.gson.Gson;
import com.yeshi.fanli.controller.admin.PushController;
import com.yeshi.fanli.dto.push.PushTypeEnum;
import com.yeshi.fanli.entity.xinge.MessageInfo;
import com.yeshi.fanli.entity.xinge.PushRecord;
import com.yeshi.fanli.log.LogHelper;
import com.yeshi.fanli.log.PushLogHelper;
import com.yeshi.fanli.service.inter.config.BusinessSystemService;
import com.yeshi.fanli.util.Constant;
import com.yeshi.fanli.util.StringUtil;
import com.yeshi.fanli.util.factory.IOSPushFactory;
 
import javapns.devices.Device;
import javapns.devices.implementations.basic.BasicDevice;
import javapns.notification.AppleNotificationServerBasicImpl;
import javapns.notification.PushNotificationManager;
import javapns.notification.PushNotificationPayload;
import javapns.notification.PushedNotification;
import net.sf.json.JSONObject;
 
@Component
public class IOSPushUtil {
 
    private static IOSPushUtil iosPushUtil;
 
    @Autowired
    private BusinessSystemService businessSystemService;
 
    @PostConstruct
    public void init() {
        iosPushUtil = this;
        iosPushUtil.businessSystemService = this.businessSystemService;
    }
 
    /**
     * 
     * 方法说明: IOS 多推
     * 
     * @author mawurui createTime 2018年5月8日 上午10:19:57
     * @param deviceToken
     * @param packages
     * @param alert
     * @return
     * @throws Exception
     */
    public static String allPushIOS(List<String> deviceTokenList, MessageInfo info, String url, int type)
            throws Exception {
 
        // if (Constant.IS_TEST)
        // return null;
 
        Gson gson = new Gson();
        PushLogHelper.iosInfo("IOS推送设备数为:" + deviceTokenList.size());
        PushLogHelper.iosInfo("IOS推送的内容为:" + gson.toJson(info));
        List<String> tokenList = new ArrayList<String>();
        for (String deviceToken : deviceTokenList) {
            tokenList.add(deviceToken);
        }
        // json自定义传值
 
        JSONObject json = null;
        if (type == PushTypeEnum.goodsdetail.getCode()) {
            Long auctionId = null;
            if (url.contains("id=")) {
                String[] sts = url.split("\\?")[1].split("&");
                for (String st : sts) {
                    if (st.contains("id=")) {
                        auctionId = Long.parseLong(st.replace("id=", "").trim());
                    }
                }
            }
            if (auctionId == null)
                throw new Exception("淘宝商品ID提取出错");
            json = IOSPushFactory.createGoodsPush(auctionId, info.getTitle(), info.getContent());
        } else if (type == PushTypeEnum.url.getCode()) {
            String shortUrl = HttpUtil.getShortLink(url);
            if (StringUtil.isNullOrEmpty(shortUrl))
                throw new Exception("获取短链出错");
            json = IOSPushFactory.createURLPush(shortUrl, info.getTitle(), info.getContent());
        } else if (type == PushTypeEnum.ZNX.getCode()) {
            json = IOSPushFactory.createZNXPush(info.getTitle(), info.getContent());
        } else if (type == PushTypeEnum.weex.getCode()) {
            String shortUrl = HttpUtil.getShortLink(url);
            if (StringUtil.isNullOrEmpty(shortUrl))
                throw new Exception("获取短链出错");
            json = IOSPushFactory.createWEEXPush(shortUrl, info.getTitle(), info.getContent());
        } else if (type == PushTypeEnum.baichuan.getCode()) {
            String shortUrl = url;
            // HttpUtil.getShortLink(url);
            // if (StringUtil.isNullOrEmpty(shortUrl))
            // throw new Exception("获取短链出错");
            json = IOSPushFactory.createBaiChuanPush(shortUrl, info.getTitle(), info.getContent());
        } else if (type == PushTypeEnum.welfare.getCode()) {
            json = IOSPushFactory.createWelfarePush(info.getTitle(), info.getContent());
        } else if (type == PushTypeEnum.signin.getCode()) {
            json = IOSPushFactory.createUserSignInPush(info.getTitle(), info.getContent());
        }
 
        // 分组推送 每50个设备为一组
 
        InputStream certificate = IOSPushUtil.class.getClassLoader()
                .getResourceAsStream("certificate/pushCertificate.p12"); // 读取.p12文件
        String certificatePassword = Constant.systemCommonConfig.getIosPushCertificatePwd();
        if (tokenList != null && tokenList.size() > 0) {
            int pageSize = 50;
            int page = tokenList.size() % pageSize == 0 ? tokenList.size() / pageSize : tokenList.size() / pageSize + 1;
            for (int i = 0; i < page; i++) {
                int start = i * pageSize;
                int end = start + pageSize;
                if (end > tokenList.size())
                    end = tokenList.size();
                pushIOS(tokenList.subList(start, end), json, certificate, certificatePassword);
            }
 
        }
 
        return null;
    }
 
    public static String pushIOS(List<String> deviceTokenList, JSONObject json, InputStream certificate,
            String certificatePWD) throws Exception {
        List<String> tokenList = new ArrayList<String>();
        for (String deviceToken : deviceTokenList) {
            tokenList.add(deviceToken);
        }
        while (json.toString().getBytes().length > 256) {
            // 首先削减内容,然后削减标题
            String title = json.optJSONObject("aps").optJSONObject("alert").optString("title");
            String body = json.optJSONObject("aps").optJSONObject("alert").optString("body");
            if (StringUtil.isNullOrEmpty(body) || body.length() < 4) {
                // 削减标题
                if (!StringUtil.isNullOrEmpty(title) && body.length() > 6) {
                    json.optJSONObject("aps").optJSONObject("alert").put("title",
                            title.substring(0, title.length() - 1));
                    continue;
                }
            } else {
                json.optJSONObject("aps").optJSONObject("alert").put("body", body.substring(0, body.length() - 1));
                continue;
            }
        }
 
        LogHelper.test("IOS推送的字节数" + json.toString().getBytes().length);
        PushNotificationPayload payLoad = new PushNotificationPayload();
        payLoad = PushNotificationPayload.fromJSON(json.toString());
 
        PushNotificationManager pushManager = new PushNotificationManager();
        // true:表示的是产品线上发布推送服务 false:表示的是产品测试推送服务
        if (Constant.IS_TEST)
            pushManager.initializeConnection(new AppleNotificationServerBasicImpl(certificate, certificatePWD, false));
        else
            pushManager.initializeConnection(new AppleNotificationServerBasicImpl(certificate, certificatePWD, true));
 
        List<Device> deviceList = new ArrayList<Device>();
        for (String token : tokenList) {
            if (!StringUtil.isNullOrEmpty(token))
                deviceList.add(new BasicDevice(token));
        }
        // 开始推送
        List<PushedNotification> notificationList = pushManager.sendNotifications(payLoad, deviceList);
        Gson gson = new Gson();
        if (notificationList != null)
            for (PushedNotification notification : notificationList) {
                PushLogHelper.iosInfo(gson.toJson(notification));
            }
        pushManager.stopConnection();
        return null;
    }
 
    /**
     * 
     * @author mawurui createTime 2018年5月8日 下午12:12:19
     * @param info
     * @param json
     * @param pushRecord
     * @return
     * @throws Exception
     */
    public static int allFanLiQuanDevice(System b_IOS, List<String> deviceTokenList, String PACKAGES, String title,
            String content, String url, PushRecord pushRecord, int type) throws Exception {
 
        return pushApp(deviceTokenList, PACKAGES, title, content, b_IOS, url, pushRecord, type);
    }
 
    /**
     * 
     * @param info
     * @param params
     * @param pushRecord
     * @return 1:都成功 2:仅android 成功 3.仅IOS成功 4.都失败
     * @throws Exception
     */
    private static int pushApp(List<String> deviceTokenList, String PACKAGES, String title, String content,
            System b_IOS, String url, PushRecord pushRecord, int type) throws Exception {
        MessageInfo info = new MessageInfo();
        info.setTitle(title);
        info.setContent(content);
        String IOS = allPushIOS(deviceTokenList, info, url, type);
        LogHelper.userInfo("IOS的推送日志:" + IOS);
        pushRecord.setIosPushId(IOS);
        if (IOS != null) {
            return 1;
        } else {
            return 4;
        }
    }
 
    /**
     * 执行推送
     * 
     * @param tokenList
     * @param json
     * @throws Exception
     */
    public static void executePushIOS(List<String> tokenList, JSONObject json) throws Exception {
        InputStream certificate = IOSPushUtil.class.getClassLoader()
                .getResourceAsStream("certificate/pushCertificate.p12"); // 读取.p12文件
        String certificatePassword = Constant.systemCommonConfig.getIosPushCertificatePwd();
        pushIOS(tokenList, json, certificate, certificatePassword);
    }
 
    /**
     * 
     * 方法说明: IOS 多推
     * 
     * @author mawurui createTime 2018年5月8日 上午10:19:57
     * @param deviceToken
     * @param packages
     * @param alert
     * @return
     * @throws Exception
     */
    public static JSONObject getJSONObject(MessageInfo info, String url, int type) throws Exception {
 
        // json自定义传值
        JSONObject json = null;
        if (type == PushTypeEnum.goodsdetail.getCode()) {
            Long auctionId = null;
            if (url.contains("id=")) {
                String[] sts = url.split("\\?")[1].split("&");
                for (String st : sts) {
                    if (st.contains("id=")) {
                        auctionId = Long.parseLong(st.replace("id=", "").trim());
                    }
                }
            }
            if (auctionId == null)
                throw new Exception("淘宝商品ID提取出错");
            json = IOSPushFactory.createGoodsPush(auctionId, info.getTitle(), info.getContent());
        } else if (type == PushTypeEnum.url.getCode()) {
            String shortUrl = HttpUtil.getShortLink(url);
            if (StringUtil.isNullOrEmpty(shortUrl))
                throw new Exception("获取短链出错");
            json = IOSPushFactory.createURLPush(shortUrl, info.getTitle(), info.getContent());
        } else if (type == PushTypeEnum.ZNX.getCode()) {
            json = IOSPushFactory.createZNXPush(info.getTitle(), info.getContent());
        } else if (type == PushTypeEnum.weex.getCode()) {
            String shortUrl = HttpUtil.getShortLink(url);
            if (StringUtil.isNullOrEmpty(shortUrl))
                shortUrl = url;
            json = IOSPushFactory.createWEEXPush(shortUrl, info.getTitle(), info.getContent());
        } else if (type == PushTypeEnum.baichuan.getCode()) {
            String shortUrl = HttpUtil.getShortLink(url);
            if (StringUtil.isNullOrEmpty(shortUrl))
                shortUrl = url;
            json = IOSPushFactory.createBaiChuanPush(shortUrl, info.getTitle(), info.getContent());
        } else if (type == PushTypeEnum.signin.getCode()) {
            json = IOSPushFactory.createUserSignInPush(info.getTitle(), info.getContent());
        }
 
        return json;
    }
}