Subversion Repositories SmartDukaan

Rev

Rev 3369 | Rev 3390 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
3339 mandeep.dh 1
/**
2
 * 
3
 */
4
package in.shop2020.util;
5
 
6
import in.shop2020.crm.Activity;
7
import in.shop2020.crm.ActivityType;
8
import in.shop2020.crm.CRMService.Client;
9
import in.shop2020.crm.Ticket;
10
import in.shop2020.crm.TicketCategory;
11
import in.shop2020.crm.TicketPriority;
12
import in.shop2020.crm.TicketStatus;
13
import in.shop2020.model.v1.user.User;
14
import in.shop2020.model.v1.user.UserContextException;
15
import in.shop2020.thrift.clients.CRMClient;
16
import in.shop2020.thrift.clients.UserClient;
17
 
18
import java.io.IOException;
19
import java.text.ParseException;
20
import java.util.Date;
21
import java.util.regex.Matcher;
22
import java.util.regex.Pattern;
23
 
24
import javax.mail.Message;
25
import javax.mail.MessagingException;
3368 mandeep.dh 26
import javax.mail.Multipart;
27
import javax.mail.Part;
3339 mandeep.dh 28
 
29
import org.apache.commons.logging.Log;
30
import org.apache.commons.logging.LogFactory;
31
import org.apache.thrift.TException;
32
import org.apache.thrift.transport.TTransportException;
33
 
34
/**
35
 * @author mandeep
36
 * 
37
 */
38
public class CRMEmailProcessor {
3368 mandeep.dh 39
    private static final int DESCRIPTION_MAX_WIDTH = 1900;
3369 mandeep.dh 40
    private static final String MAILOR_DAEMON_EMAIL_ID = "mailer-daemon@googlemail.com";
3339 mandeep.dh 41
    private static final Log log                   = LogFactory
42
                                                           .getLog(CRMEmailProcessor.class);
43
    private Client           client;
44
 
45
    public void processEmail(Message message) throws MessagingException,
46
            IOException, TException, UserContextException {
3369 mandeep.dh 47
        // Ignoring mails from Mailor daemon
48
        if (MAILOR_DAEMON_EMAIL_ID.equals(parseEmailId(message.getFrom()[0].toString()))) {
49
            return;
50
        }
51
 
3339 mandeep.dh 52
        Long ticketId = parseTicketId(message);
53
 
54
        if (ticketId != null) {
55
            log.info("Response for Ticket: " + ticketId + ": " + message);
56
            updateTicket(ticketId, message);
57
        } else {
58
            log.info("Mail not recognized as CRM ticket response with subject: "
59
                    + message.getSubject());
60
            log.info("Creating ticket for the same");
61
            createTicket(message);
62
        }
63
    }
64
 
65
    private Long parseTicketId(Message message) throws MessagingException {
66
        Long ticketId = null;
67
        String subject = message.getSubject();
68
        if (subject != null) {
69
            Pattern p = Pattern.compile("^.*"
70
                    + CRMConstants.CRM_SUBJECT_PREFIX_FOR_TICKET_ID
71
                    + "(\\d+).*$");
72
            Matcher m = p.matcher(subject);
73
            if (m.matches()) {
74
                ticketId = Long.parseLong(m.group(1));
75
            }
76
        }
77
 
78
        return ticketId;
79
    }
80
 
81
    public Date getLastProcessedTimestamp() throws ParseException, TException {
3373 mandeep.dh 82
        client = new CRMClient().getClient();
3339 mandeep.dh 83
        return new Date(client.getLastEmailProcessedTimestamp());
84
    }
85
 
86
    public void updateLastProcessedTimestamp(Date date) throws TException {
3340 mandeep.dh 87
        client = new CRMClient().getClient();
3339 mandeep.dh 88
        client.updateLastEmailProcessedTimestamp(date.getTime());
89
    }
90
 
91
    private void updateTicket(Long ticketId, Message message) {
92
        try {
3373 mandeep.dh 93
            client = new CRMClient().getClient();
3339 mandeep.dh 94
            Ticket ticket = client.getTicket(ticketId);
95
            Activity activity = new Activity();
96
            activity.setTicketId(ticketId);
97
            activity.setTicketAssigneeId(ticket.getAssigneeId());
98
            activity.setTicketCategory(ticket.getCategory());
99
            activity.setTicketDescription(ticket.getDescription());
100
            activity.setTicketPriority(ticket.getPriority());
101
            activity.setTicketStatus(ticket.getStatus());
102
            activity.setType(ActivityType.RECEIVED_EMAIL_FROM_CUSTOMER);
103
            activity.setCreatorId(CRMConstants.ADMIN_AGENT_ID);
104
 
105
            if (ticket.isSetCustomerId()) {
106
                activity.setCustomerId(ticket.getCustomerId());
107
            }
108
 
109
            activity.setDescription(convertMessageToText(message));
3368 mandeep.dh 110
 
111
            if (TicketStatus.CLOSED.equals(ticket.getStatus())) {
112
                ticket.setStatus(TicketStatus.REOPEN);
113
            }
114
 
3373 mandeep.dh 115
            client = new CRMClient().getClient();
3339 mandeep.dh 116
            client.updateTicket(ticket, activity);
117
        } catch (TTransportException e) {
118
            log.error("Could not update ticket " + ticketId + " with mail "
119
                    + message, e);
120
        } catch (TException e) {
121
            log.error("Could not update ticket " + ticketId + " with mail "
122
                    + message, e);
123
        } catch (MessagingException e) {
124
            log.error("Could not update ticket " + ticketId + " with mail "
125
                    + message, e);
126
        } catch (IOException e) {
127
            log.error("Could not update ticket " + ticketId + " with mail "
128
                    + message, e);
129
        }
130
    }
131
 
132
    private void createTicket(Message message) throws MessagingException,
133
            IOException, TException, UserContextException {
134
        String description = convertMessageToText(message);
135
        Ticket ticket = new Ticket();
136
        ticket.setCreatorId(CRMConstants.ADMIN_AGENT_ID);
137
        ticket.setCategory(TicketCategory.OTHER);
138
        String customerEmailId = parseEmailId(message.getFrom()[0].toString());
139
 
140
        in.shop2020.model.v1.user.UserContextService.Client userClient = new UserClient()
141
                .getClient();
142
        User user = userClient.getUserByEmail(customerEmailId);
143
 
144
        if (user == null || user.getUserId() == -1) {
145
            ticket.setCustomerEmailId(customerEmailId);
146
        } else {
147
            ticket.setCustomerId(user.getUserId());
148
        }
149
 
150
        ticket.setDescription(description);
151
        ticket.setPriority(TicketPriority.MEDIUM);
152
        ticket.setStatus(TicketStatus.OPEN);
153
 
154
        log.info("Creating activity!");
155
        Activity activity = new Activity();
156
        activity.setDescription(description);
157
        activity.setTicketCategory(ticket.getCategory());
158
        activity.setTicketDescription(ticket.getDescription());
159
        activity.setTicketPriority(ticket.getPriority());
160
        activity.setTicketStatus(ticket.getStatus());
161
        activity.setType(ActivityType.RECEIVED_EMAIL_FROM_CUSTOMER);
162
        activity.setCreatorId(CRMConstants.ADMIN_AGENT_ID);
163
 
3373 mandeep.dh 164
        client = new CRMClient().getClient();
3339 mandeep.dh 165
        client.insertTicket(ticket, activity);
166
    }
167
 
168
    // parsing email Id from strings like
3368 mandeep.dh 169
    // "Pankaj Jain <ponkoj@hotmail.com>"
3339 mandeep.dh 170
    private String parseEmailId(String address) {
171
        Pattern p = Pattern.compile("^.*<(.+)>.*$");
172
        Matcher m = p.matcher(address);
173
        if (m.matches()) {
174
            address = m.group(1);
175
        }
176
 
177
        return address;
178
    }
179
 
180
    private String convertMessageToText(Message message)
181
            throws MessagingException, IOException {
3368 mandeep.dh 182
        String messageContent = getText(message);
3339 mandeep.dh 183
 
3368 mandeep.dh 184
        String content = "From: " + message.getFrom()[0].toString()
185
                + "\n\nSubject: " + message.getSubject() + "\n\nBody: "
186
                + messageContent;
3339 mandeep.dh 187
 
188
        if (content.length() > DESCRIPTION_MAX_WIDTH) {
189
            content = content.substring(0, DESCRIPTION_MAX_WIDTH);
3368 mandeep.dh 190
            content += "\n\nTHIS TEXT IS TRUNCATED. PLEASE VISIT INBOX TO SEE COMPLETE DETAILS.";
3339 mandeep.dh 191
        }
192
 
193
        return content;
194
    }
3368 mandeep.dh 195
 
196
    /**
197
     * Return the primary text content of the message.
198
     */
199
    private String getText(Part p) throws MessagingException, IOException {
200
        if (p.isMimeType("text/*")) {
201
            String s = (String) p.getContent();
202
            return s;
203
        }
204
 
205
        if (p.isMimeType("multipart/alternative")) {
206
            // prefer plain text over html text
207
            Multipart mp = (Multipart) p.getContent();
208
            String text = null;
209
            for (int i = 0; i < mp.getCount(); i++) {
210
                Part bp = mp.getBodyPart(i);
211
                if (bp.isMimeType("text/html")) {
212
                    if (text == null)
213
                        text = getText(bp);
214
                    continue;
215
                } else if (bp.isMimeType("text/plain")) {
216
                    String s = getText(bp);
217
                    if (s != null)
218
                        return s;
219
                } else {
220
                    return getText(bp);
221
                }
222
            }
223
            return text;
224
        } else if (p.isMimeType("multipart/*")) {
225
            Multipart mp = (Multipart) p.getContent();
226
            for (int i = 0; i < mp.getCount(); i++) {
227
                String s = getText(mp.getBodyPart(i));
228
                if (s != null)
229
                    return s;
230
            }
231
        }
232
 
233
        return null;
234
    }
3339 mandeep.dh 235
}