Subversion Repositories SmartDukaan

Rev

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