aboutsummaryrefslogtreecommitdiff
path: root/juick-notifications/src/main/java/com/juick/components/APNSManager.java
blob: 2c7cfce44f5c765f8ebd68cd02227b259beac29a (plain) (blame)
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
package com.juick.components;

import com.juick.ExternalToken;
import com.juick.Message;
import com.juick.User;
import com.juick.formatters.PlainTextFormatter;
import com.juick.service.component.*;
import com.turo.pushy.apns.ApnsClient;
import com.turo.pushy.apns.ApnsClientBuilder;
import com.turo.pushy.apns.PushNotificationResponse;
import com.turo.pushy.apns.auth.ApnsSigningKey;
import com.turo.pushy.apns.util.ApnsPayloadBuilder;
import com.turo.pushy.apns.util.SimpleApnsPushNotification;
import com.turo.pushy.apns.util.concurrent.PushNotificationResponseListener;
import io.netty.util.concurrent.Future;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.inject.Inject;
import java.io.File;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.List;
import java.util.Optional;

public class APNSManager implements NotificationListener {
    private static Logger logger = LoggerFactory.getLogger(APNSManager.class);

    private ApnsClient apns;
    @Value("${ios_p8_key:}")
    private String p8key;
    @Value("${ios_app_id:}")
    private String topic;
    @Value("${ios_team_id:}")
    private String teamId;
    @Value("${ios_key_id:}")
    private String keyId;
    @Inject
    private NotificationsManager notificationsManager;
    @PostConstruct
    public void initialize() throws NoSuchAlgorithmException, InvalidKeyException, IOException {
        apns = new ApnsClientBuilder()
                .setApnsServer(ApnsClientBuilder.PRODUCTION_APNS_HOST)
                .setSigningKey(ApnsSigningKey.loadFromPkcs8File(new File(p8key),
                        teamId, keyId))
                .build();
    }
    @Override
    public void processMessageEvent(MessageEvent messageEvent) {
        com.juick.Message jmsg = messageEvent.getMessage();
        List<User> users = messageEvent.getUsers();
        ApnsPayloadBuilder apnsPayloadBuilder = new ApnsPayloadBuilder();
        apnsPayloadBuilder.addCustomProperty("mid", jmsg.getMid());
        apnsPayloadBuilder.addCustomProperty("uname", jmsg.getUser().getName());
        String post = PlainTextFormatter.formatPost(jmsg);
        String[] parts = post.split("\n", 2);
        apnsPayloadBuilder.setAlertTitle(parts[0]).setAlertBody(parts[1]);
        users.forEach( user -> {
            apnsPayloadBuilder.setBadgeNumber(user.getUnreadCount());
            String payload = apnsPayloadBuilder.buildWithDefaultMaximumLength();
            user.getTokens().stream().filter(t -> t.getType().equals("apns"))
                    .map(ExternalToken::getToken).forEach(token -> {
                Future<PushNotificationResponse<SimpleApnsPushNotification>> notification = apns.sendNotification(
                        new SimpleApnsPushNotification(token, topic, payload));
                notification.addListener((PushNotificationResponseListener<SimpleApnsPushNotification>) future -> {
                    if (future.isSuccess()) {
                        processAPNSResponse(token, future.getNow());
                    } else {
                        logger.warn("APNS error ", future.cause());
                    }
                });
            });
        });
    }

    @Override
    public void processSubscribeEvent(SubscribeEvent subscribeEvent) {

    }

    @Override
    public void processLikeEvent(LikeEvent likeEvent) {

    }

    @Override
    public void processPingEvent(PingEvent pingEvent) {

    }

    @Override
    public void processMessageReadEvent(MessageReadEvent messageReadEvent) {
        User user = messageReadEvent.getUser();
        ApnsPayloadBuilder apnsPayloadBuilder = new ApnsPayloadBuilder();
        apnsPayloadBuilder.setBadgeNumber(user.getUnreadCount());
        String payload = apnsPayloadBuilder.buildWithDefaultMaximumLength();
        user.getTokens().stream().filter(t -> t.getType().equals("apns"))
                .map(ExternalToken::getToken).forEach(token -> {
            Future<PushNotificationResponse<SimpleApnsPushNotification>> notification = apns.sendNotification(
                    new SimpleApnsPushNotification(token, topic, payload));
            notification.addListener((PushNotificationResponseListener<SimpleApnsPushNotification>) future -> {
                if (future.isSuccess()) {
                    processAPNSResponse(token, future.getNow());
                } else {
                    logger.warn("APNS error ", future.cause());
                }
            });
        });
    }

    @Override
    public void processTopEvent(TopEvent topEvent) {
        Message message = topEvent.getMessage();
        ApnsPayloadBuilder apnsPayloadBuilder = new ApnsPayloadBuilder();
        message.getUser().getTokens().stream().filter(t -> t.getType().equals("apns"))
                .map(ExternalToken::getToken).forEach( token -> {
            String payload = apnsPayloadBuilder.setAlertTitle("Top").setAlertBody("Your message became popular!")
                    .addCustomProperty("mid", message.getMid())
                    .addCustomProperty("uname", message.getUser().getName())
                    .buildWithDefaultMaximumLength();
            Future<PushNotificationResponse<SimpleApnsPushNotification>> notification = apns.sendNotification(
                    new SimpleApnsPushNotification(token, topic, payload));
            notification.addListener((PushNotificationResponseListener<SimpleApnsPushNotification>) future -> {
                if (future.isSuccess()) {
                    processAPNSResponse(token, future.getNow());
                } else {
                    logger.warn("APNS error ", future.cause());
                }
            });
        });
    }

    @PreDestroy
    public void close() {
        apns.close();
    }

    private void processAPNSResponse(String token, PushNotificationResponse<SimpleApnsPushNotification> pushNotificationResponse) {
        if (pushNotificationResponse.isAccepted()) {
            logger.info("APNS accepted: {}", token);
        } else {
            String reason = pushNotificationResponse.getRejectionReason();
            logger.info("APNS rejected: {}", reason);
            if (reason.equals("BadDeviceToken")) {
                notificationsManager.getInvalidAPNSTokens().add(token);
            }
        }
        Optional<Date> invalidationDate = Optional.ofNullable(
                pushNotificationResponse.getTokenInvalidationTimestamp());
        invalidationDate.ifPresent(date -> {
            if (date.before(new Date())) {
                logger.info("Token invalidated: {}", token);
                notificationsManager.getInvalidAPNSTokens().add(token);
            }
        });
    }
}