Subversion Repositories SmartDukaan

Rev

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