Subversion Repositories SmartDukaan

Rev

Rev 3340 | Rev 3369 | 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;
3339 mandeep.dh 40
    private static final Log log                   = LogFactory
41
                                                           .getLog(CRMEmailProcessor.class);
42
    private Client           client;
43
 
44
    public CRMEmailProcessor() {
45
        try {
46
            client = new CRMClient().getClient();
47
        } catch (TTransportException e) {
48
            log.error("Could not create client", e);
49
        }
50
    }
51
 
52
    public void processEmail(Message message) throws MessagingException,
53
            IOException, TException, UserContextException {
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 {
84
        return new Date(client.getLastEmailProcessedTimestamp());
85
    }
86
 
87
    public void updateLastProcessedTimestamp(Date date) throws TException {
3340 mandeep.dh 88
        client = new CRMClient().getClient();
3339 mandeep.dh 89
        client.updateLastEmailProcessedTimestamp(date.getTime());
90
    }
91
 
92
    private void updateTicket(Long ticketId, Message message) {
93
        try {
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
 
3339 mandeep.dh 115
            client.updateTicket(ticket, activity);
116
        } catch (TTransportException e) {
117
            log.error("Could not update ticket " + ticketId + " with mail "
118
                    + message, e);
119
        } catch (TException e) {
120
            log.error("Could not update ticket " + ticketId + " with mail "
121
                    + message, e);
122
        } catch (MessagingException e) {
123
            log.error("Could not update ticket " + ticketId + " with mail "
124
                    + message, e);
125
        } catch (IOException e) {
126
            log.error("Could not update ticket " + ticketId + " with mail "
127
                    + message, e);
128
        }
129
    }
130
 
131
    private void createTicket(Message message) throws MessagingException,
132
            IOException, TException, UserContextException {
133
        String description = convertMessageToText(message);
134
        Ticket ticket = new Ticket();
135
        ticket.setCreatorId(CRMConstants.ADMIN_AGENT_ID);
136
        ticket.setCategory(TicketCategory.OTHER);
137
        String customerEmailId = parseEmailId(message.getFrom()[0].toString());
138
 
139
        in.shop2020.model.v1.user.UserContextService.Client userClient = new UserClient()
140
                .getClient();
141
        User user = userClient.getUserByEmail(customerEmailId);
142
 
143
        if (user == null || user.getUserId() == -1) {
144
            ticket.setCustomerEmailId(customerEmailId);
145
        } else {
146
            ticket.setCustomerId(user.getUserId());
147
        }
148
 
149
        ticket.setDescription(description);
150
        ticket.setPriority(TicketPriority.MEDIUM);
151
        ticket.setStatus(TicketStatus.OPEN);
152
 
153
        log.info("Creating activity!");
154
        Activity activity = new Activity();
155
        activity.setDescription(description);
156
        activity.setTicketCategory(ticket.getCategory());
157
        activity.setTicketDescription(ticket.getDescription());
158
        activity.setTicketPriority(ticket.getPriority());
159
        activity.setTicketStatus(ticket.getStatus());
160
        activity.setType(ActivityType.RECEIVED_EMAIL_FROM_CUSTOMER);
161
        activity.setCreatorId(CRMConstants.ADMIN_AGENT_ID);
162
 
163
        client.insertTicket(ticket, activity);
164
    }
165
 
166
    // parsing email Id from strings like
3368 mandeep.dh 167
    // "Pankaj Jain <ponkoj@hotmail.com>"
3339 mandeep.dh 168
    private String parseEmailId(String address) {
169
        Pattern p = Pattern.compile("^.*<(.+)>.*$");
170
        Matcher m = p.matcher(address);
171
        if (m.matches()) {
172
            address = m.group(1);
173
        }
174
 
175
        return address;
176
    }
177
 
178
    private String convertMessageToText(Message message)
179
            throws MessagingException, IOException {
3368 mandeep.dh 180
        String messageContent = getText(message);
181
        System.out.println(messageContent);
3339 mandeep.dh 182
 
3368 mandeep.dh 183
        String content = "From: " + message.getFrom()[0].toString()
184
                + "\n\nSubject: " + message.getSubject() + "\n\nBody: "
185
                + messageContent;
3339 mandeep.dh 186
 
187
        if (content.length() > DESCRIPTION_MAX_WIDTH) {
188
            content = content.substring(0, DESCRIPTION_MAX_WIDTH);
3368 mandeep.dh 189
            content += "\n\nTHIS TEXT IS TRUNCATED. PLEASE VISIT INBOX TO SEE COMPLETE DETAILS.";
3339 mandeep.dh 190
        }
191
 
192
        return content;
193
    }
3368 mandeep.dh 194
 
195
    /**
196
     * Return the primary text content of the message.
197
     */
198
    private String getText(Part p) throws MessagingException, IOException {
199
        if (p.isMimeType("text/*")) {
200
            String s = (String) p.getContent();
201
            return s;
202
        }
203
 
204
        if (p.isMimeType("multipart/alternative")) {
205
            // prefer plain text over html text
206
            Multipart mp = (Multipart) p.getContent();
207
            String text = null;
208
            for (int i = 0; i < mp.getCount(); i++) {
209
                Part bp = mp.getBodyPart(i);
210
                if (bp.isMimeType("text/html")) {
211
                    if (text == null)
212
                        text = getText(bp);
213
                    continue;
214
                } else if (bp.isMimeType("text/plain")) {
215
                    String s = getText(bp);
216
                    if (s != null)
217
                        return s;
218
                } else {
219
                    return getText(bp);
220
                }
221
            }
222
            return text;
223
        } else if (p.isMimeType("multipart/*")) {
224
            Multipart mp = (Multipart) p.getContent();
225
            for (int i = 0; i < mp.getCount(); i++) {
226
                String s = getText(mp.getBodyPart(i));
227
                if (s != null)
228
                    return s;
229
            }
230
        }
231
 
232
        return null;
233
    }
3339 mandeep.dh 234
}