Subversion Repositories SmartDukaan

Rev

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