Subversion Repositories SmartDukaan

Rev

Rev 15089 | Rev 15166 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
14843 amit.gupta 1
import StringIO
2
import base64
3
import gzip
4
import pymongo
13572 kshitij.so 5
import time
14843 amit.gupta 6
import urllib
14736 kshitij.so 7
import urllib2
14948 amit.gupta 8
from datetime import datetime
15152 kshitij.so 9
import random
14705 kshitij.so 10
#TODO Need to add messy stuff to conf.
14708 kshitij.so 11
con=None
14736 kshitij.so 12
headers = { 
13
            'User-agent':'Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36',
14
            'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',      
15
            'Accept-Language' : 'en-US,en;q=0.8',                     
16
            'Accept-Charset' : 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
17
            'Connection':'keep-alive',
18
            'Accept-Encoding' : 'gzip,deflate,sdch'
19
        }
15152 kshitij.so 20
PROXY_URL = "http://192.161.160.203:8800/"
21
PROXY_LIST = ['192.161.160.203:8800','173.234.194.214:8800', \
22
              '192.161.160.13:8800','173.208.39.246:8800','192.161.160.212:8800', \
23
              '173.234.194.37:8800','173.208.39.67:8800','192.161.163.249:8800', \
24
              '192.161.163.60:8800']
25
 
14843 amit.gupta 26
PUSH_NOTIFICATION_URL='http://api.profittill.com/admin/users/push'
27
DTR_API_BASIC_AUTH = base64.encodestring('%s:%s' % ("dtr", "dtr18Feb2015")).replace('\n', '')
14747 kshitij.so 28
 
14705 kshitij.so 29
def get_mongo_connection(host='localhost', port=27017):
30
    global con
31
    if con is None:
32
        print "Establishing connection %s host and port %d" %(host,port)
33
        try:
34
            con = pymongo.MongoClient(host, port)
35
        except Exception, e:
36
            print e
37
            return None
38
    return con
39
 
13572 kshitij.so 40
def to_java_date(py_timestamp):
41
    try:
42
        java_date =  int(time.mktime(py_timestamp.timetuple())) * 1000 + py_timestamp.microsecond / 1000
43
        return java_date
44
    except:
14705 kshitij.so 45
        return None
46
 
47
def getCashBack(skuId, source_id, category_id, mc, mongoHost):
48
    if not bool(mc.get("category_cash_back")):
49
        populateCashBack(mc, mongoHost)
50
    itemCashBackMap = mc.get("item_cash_back")
51
    itemCashBack = itemCashBackMap.get(skuId)
52
    if itemCashBack is not None:
53
        return itemCashBack
54
    cashBackMap = mc.get("category_cash_back")
55
    sourceCashBack = cashBackMap.get(source_id)
56
    if sourceCashBack is not None and len(sourceCashBack) > 0:
57
        for cashBack in sourceCashBack:
58
            if cashBack.get(category_id) is None:
59
                continue
60
            else:
61
                return cashBack.get(category_id)
62
    else:
63
        return {}
64
 
65
def populateCashBack(mc, mongoHost):
66
    print "Populating cashback"
67
    cashBackMap = {}
68
    itemCashBackMap = {}
69
    cashBack = list(get_mongo_connection(host=mongoHost).Catalog.CategoryCashBack.find())
70
    for row in cashBack:
71
        temp_map = {}
72
        temp_list = []
73
        if cashBackMap.has_key(row['source_id']):
74
            arr = cashBackMap.get(row['source_id'])
75
            for val in arr:
76
                temp_list.append(val)
77
            temp_map[row['category_id']] = row
78
            temp_list.append(temp_map)
79
            cashBackMap[row['source_id']] = temp_list 
80
        else:
81
            temp_map[row['category_id']] = row
82
            temp_list.append(temp_map)
83
            cashBackMap[row['source_id']] = temp_list
84
    itemCashBack = list(get_mongo_connection(host=mongoHost).Catalog.ItemCashBack.find())
85
    for row in itemCashBack:
86
        if not itemCashBackMap.has_key(row['skuId']):
87
            itemCashBackMap[row['skuId']] = row
88
    mc.set("item_cash_back", itemCashBackMap, 24 * 60 * 60)
89
    mc.set("category_cash_back", cashBackMap, 24 * 60 * 60)
90
 
14736 kshitij.so 91
def ungzipResponse(r):
92
    headers = r.info()
93
    if headers.get('Content-Encoding')=='gzip':
94
        url_f = StringIO.StringIO(r.read())
95
        gz = gzip.GzipFile(fileobj=url_f)
96
        html = gz.read()
97
        gz.close()
98
        return html
99
    return r.read()
100
 
101
 
102
def fetchResponseUsingProxy(url, headers=headers):
15152 kshitij.so 103
    PROXY_URL = PROXY_LIST[random.randint(0, len(PROXY_LIST) -1)]
104
    print PROXY_URL
14993 amit.gupta 105
    proxy = urllib2.ProxyHandler({'http': PROXY_URL})
106
    opener = urllib2.build_opener(proxy)
107
    urllib2.install_opener(opener)
14736 kshitij.so 108
    req = urllib2.Request(url,headers=headers)
109
    response = urllib2.urlopen(req)
110
    response_data = ungzipResponse(response)
111
    response.close()
112
    return response_data
113
 
14843 amit.gupta 114
def sendNotification(userIds, campaignName, title, message,notificationtype, url):
115
    usertuples = ()
116
    count = -1
117
    for userId in userIds:
118
        count += 1
119
        usertuples += (("userIds[" + str(count) + "]", userId),)
120
    parameters = usertuples + (
121
                   ("User[name]", campaignName), 
122
                   ("User[title]", title ), 
123
                   ("User[message]", message), 
124
                   ("User[type]", notificationtype), 
125
                   ("User[url]", url),)
126
    parameters = urllib.urlencode(parameters)
14987 amit.gupta 127
    #print parameters
14843 amit.gupta 128
    pushpostrequest = urllib2.Request(PUSH_NOTIFICATION_URL, parameters, headers=headers)
129
    pushpostrequest.add_header("Authorization", "Basic %s" % DTR_API_BASIC_AUTH)
14845 amit.gupta 130
    urllib2.urlopen(pushpostrequest).read()
14948 amit.gupta 131
 
132
def getCurrTimeStamp():
133
    return toTimeStamp(datetime.now())
134
 
135
def toTimeStamp(dateTimeObj):
136
    return int(time.mktime(dateTimeObj.timetuple()))
14987 amit.gupta 137
def fromTimeStamp(timestamp):
138
    return datetime.fromtimestamp(timestamp)