Subversion Repositories SmartDukaan

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
8842 anupam.sin 1
package in.shop2020.serving.interceptors;
2
 
3
import in.shop2020.datalogger.EventType;
4
import in.shop2020.model.v1.user.Affiliate;
5
import in.shop2020.serving.services.UserSessionInfo;
6
import in.shop2020.serving.utils.DesEncrypter;
7
import in.shop2020.thrift.clients.UserClient;
8
import in.shop2020.utils.DataLogger;
9
 
10
import java.util.Date;
11
import java.util.HashMap;
12
import java.util.HashSet;
13
import java.util.Map;
14
import java.util.Set;
15
 
16
import javax.servlet.http.Cookie;
17
import javax.servlet.http.HttpServletRequest;
18
import javax.servlet.http.HttpServletResponse;
19
 
20
import org.apache.log4j.Logger;
21
import org.apache.struts2.ServletActionContext;
22
 
23
import com.opensymphony.xwork2.ActionInvocation;
24
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
25
 
26
public class TrackingInterceptor extends AbstractInterceptor {
27
 
28
    private static final long serialVersionUID = 1L;
29
    private static Logger log = Logger.getLogger(TrackingInterceptor.class);
30
 
31
    private static final int SECONDS_IN_YEAR = 60 * 60 * 24 * 365;
32
    private static final int SECONDS_IN_DAY = 60 * 60 * 24;
33
    public static final String AFF_COOKIE = "uafc";
34
    public static final String SRC_COOKIE = "usrcc";
35
    public static final String SESSION_SRC_COOKIE = "sess_srcc";
36
    public static final String SRC_TIME_COOKIE = "usrctc";
37
    public static final String SESSION_SRC_TIME_COOKIE = "sess_srctc";
38
    public static final String SESSION_ID_COOKIE = "sess_idc";
39
    public static final String ENCRIPTION_STRING = "Saholic";
40
    private static final Set<String> paidAffIds;
41
 
42
    private String cookieDomain = "";
43
    private Cookie affCookie = null;
44
    private Cookie firstSourceCookie = null;
45
    private Cookie sessionSourceCookie = null;
46
    private Cookie firstSourceTimeCookie = null;
47
    private Cookie sessionSourceTimeCookie = null;
48
    private Cookie sessionIdCookie = null;
49
    private Map<String, Cookie> cookiesMap = null;
50
 
51
    private HttpServletRequest request;
52
    private HttpServletResponse response;
53
    private String referer;
54
    private String affId = null;
55
    private String utmSrc = null;
56
 
57
    static {
58
        paidAffIds = new HashSet<String>();
59
        paidAffIds.add("6");
60
        paidAffIds.add("38");
61
        paidAffIds.add("41");
62
        paidAffIds.add("43");
63
        paidAffIds.add("45");
64
    }
65
 
66
    public void setCookieDomain(String cookieDomain) {
67
        this.cookieDomain = cookieDomain;
68
    }
69
 
70
    @Override
71
    public String intercept(ActionInvocation invocation) throws Exception {
72
        request = ServletActionContext.getRequest();
73
        response = ServletActionContext.getResponse();
74
        referer = request.getHeader("referer");
75
        affId = request.getParameter("afid");
76
        utmSrc = request.getParameter("utm_source");
77
 
78
        createCookiesMap();
79
        updateFirstSourceCookie();
80
        updateSessionSourceCookie();
81
 
82
        updateAffCookie();
83
        return invocation.invoke();
84
    }
85
 
86
    /**
87
     * Update first source cookie
88
     * 
89
     */
90
    private void updateFirstSourceCookie() {
91
        firstSourceCookie = (Cookie) cookiesMap.get(SRC_COOKIE);
92
        if (firstSourceCookie != null) {
93
            return;
94
        }
95
        String src = getSource();
96
        DesEncrypter des = new DesEncrypter(ENCRIPTION_STRING);
97
        String sourceCookieVal = des.encrypt(src);
98
 
99
        firstSourceCookie = createCookie(SRC_COOKIE, cookieDomain, sourceCookieVal, SECONDS_IN_YEAR);
100
        firstSourceTimeCookie = createCookie(SRC_TIME_COOKIE, cookieDomain, Long.toString((new Date()).getTime()), SECONDS_IN_YEAR);
101
 
102
        cookiesMap.put(SRC_COOKIE, firstSourceCookie);
103
        cookiesMap.put(SRC_TIME_COOKIE, firstSourceTimeCookie);
104
 
105
        response.addCookie(firstSourceCookie);
106
        response.addCookie(firstSourceTimeCookie);
107
    }
108
 
109
    private Cookie createCookie(String name, String domain, String value, Integer age) {
110
        Cookie cookie = new Cookie(name, value);
111
        if (age != null) {
112
            cookie.setMaxAge(age);
113
        }
114
        cookie.setPath("/");
115
        if (!domain.isEmpty()) {
116
            cookie.setDomain(domain);
117
        }
118
        return cookie;
119
    }
120
 
121
    /**
122
     * Update first source cookie
123
     * 
124
     */
125
    private void updateSessionSourceCookie() {
126
        sessionSourceCookie = (Cookie) cookiesMap.get(SESSION_SRC_COOKIE);
127
        if (sessionSourceCookie != null) {
128
            if (referer == null || referer.isEmpty() || referer.startsWith("http://www.saholic.com") || referer.startsWith("http://local.shop2020.in")) {
129
                log.info("No change in session cookie");
130
                return;
131
            }
132
        }
133
        String src = getSource();
134
 
135
        DesEncrypter des = new DesEncrypter(ENCRIPTION_STRING);
136
        String sessionSourceCookieVal = des.encrypt(src);
137
 
138
        //session source
139
        sessionSourceCookie = createCookie(SESSION_SRC_COOKIE, cookieDomain, sessionSourceCookieVal, null);
140
        cookiesMap.put(SESSION_SRC_COOKIE, sessionSourceCookie);
141
        log.info("new session cookie : " + sessionSourceCookieVal);
142
 
143
        //session time
144
        sessionSourceTimeCookie = createCookie(SESSION_SRC_TIME_COOKIE, cookieDomain, Long.toString((new Date()).getTime()), null);
145
        cookiesMap.put(SESSION_SRC_TIME_COOKIE, sessionSourceTimeCookie);
146
 
147
        UserSessionInfo userInfo = (UserSessionInfo) request
148
            .getAttribute(UserInterceptor.USER_INFO_COOKIE_NAME);
149
 
150
        //session id for chaining user actions over one year 
151
        sessionIdCookie = (Cookie) cookiesMap.get(SESSION_ID_COOKIE);
152
        if (sessionIdCookie == null) {
153
            String sessionId = request.getSession().getId();
154
            sessionIdCookie = createCookie(SESSION_ID_COOKIE, cookieDomain, sessionId, SECONDS_IN_YEAR);
155
            cookiesMap.put(SESSION_ID_COOKIE, sessionIdCookie);
156
 
157
            response.addCookie(sessionIdCookie);
158
            String firstSrc = "";
159
            firstSourceCookie = (Cookie) cookiesMap.get(SRC_COOKIE);
160
            if (firstSourceCookie != null) {
161
                firstSrc = des.decrypt(firstSourceCookie.getValue());
162
            }
163
            DataLogger.logData(EventType.NEW_SESSION, cookiesMap.get(SESSION_ID_COOKIE).getValue(),
164
                    userInfo.getUserId(), userInfo.getEmail(), src, firstSrc);
165
        }
166
 
167
        response.addCookie(sessionSourceCookie);
168
        response.addCookie(sessionSourceTimeCookie);
169
    }
170
 
171
    private void createCookiesMap() {
172
        cookiesMap = new HashMap<String, Cookie>();
173
        Cookie[] cookies = request.getCookies();
174
        // This check is necessary for the first request when no cookies are
175
        // sent.
176
        if (cookies == null)
177
            return;
178
        for (Cookie cookie : cookies) {
179
            cookiesMap.put(cookie.getName(), cookie);
180
        }
181
    }
182
 
183
    private void updateAffCookie() {
184
        try {
185
            if(affId == null || affId.isEmpty()) {
186
                if (referer != null && !referer.isEmpty() && !referer.startsWith("http://www.saholic.com") && !referer.startsWith("http://www.shop2020.in")) {
187
                    Cookie affCookie = cookiesMap.get(AFF_COOKIE);
188
                    if(affCookie != null) {
189
                        affCookie.setDomain(cookieDomain);
190
                        affCookie.setPath("/");
191
                        affCookie.setValue("");
192
                        affCookie.setMaxAge(0);
193
                        response.addCookie(affCookie);
194
                    }
195
                }
196
                return;
197
            }
198
            UserClient userContextServiceClient = new UserClient();
199
            in.shop2020.model.v1.user.UserContextService.Client userClient = userContextServiceClient.getClient();
200
            long affiliateId = Long.parseLong(affId);
201
            Affiliate affiliate = userClient.getAffiliateById(affiliateId);
202
            if (affiliate != null) {
203
                affCookie = (Cookie) cookiesMap.get(AFF_COOKIE);
204
                if (affCookie != null) {
205
                    Long.parseLong(affCookie.getValue());
206
                    if (affiliateId == Long.parseLong(affCookie.getValue())) {
207
                        return;
208
                    }
209
                }
210
                // create new aff cookie if affCookie ==null or affiliateId() != affCookie.
211
                Cookie newAffCookie = new Cookie(AFF_COOKIE, String.valueOf(affiliateId));
212
                newAffCookie.setMaxAge(SECONDS_IN_DAY * 5);
213
                newAffCookie.setPath("/");
214
                if (!cookieDomain.isEmpty()) {
215
                    newAffCookie.setDomain(cookieDomain);
216
                }
217
                cookiesMap.put(AFF_COOKIE, newAffCookie);
218
                response.addCookie(newAffCookie);
219
            }
220
        } catch (Exception e) {
221
            log.error("Failed to update affcookie.", e);
222
        }
223
	}
224
 
225
    private String getSource() {    
226
        String src = "";
227
 
228
        /* 
229
         * we are using http://email/ so that it is parsed properly in 
230
         * DailyProductwithSourceAggregatorServlet.getSource()
231
         */
232
        if (utmSrc != null) {
233
            src = "NEWSLETTER : (http://email/)";
234
        }
235
        else if (referer == null || referer.isEmpty()) {
236
            String queryString = request.getQueryString();
237
            queryString = queryString == null? "" : "?" + queryString;
238
            src = "DIRECT : " + "(" + request.getRequestURL() + "/" + queryString + ")";
239
        } 
240
        else if (referer.startsWith("http://www.saholic.com") || referer.startsWith("http://www.shop2020.in")) {
241
            src = "DIRECT : " + "(" + referer + ")";
242
        } 
243
        else if(paidAffIds.contains(affId)) {
244
            src = "PAID : " + "(" + referer + ")";
245
        }
246
        else if (referer.contains("google.co")) {
247
            src = "ORGANIC : " + "(" + referer + ")";
248
        }
249
        else {
250
            src = referer;
251
        }
252
        return src;
253
    }
254
}