Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
15691 manish.sha 1
#!/usr/bin/python
2
 
3
import threading
4
import time
16386 manish.sha 5
import datetime
15691 manish.sha 6
 
7
import MySQLdb
8
from elixir import *
9
from sqlalchemy.orm.exc import NoResultFound, MultipleResultsFound
10
from sqlalchemy.sql import func
11
from sqlalchemy.sql.expression import and_, or_, desc, not_, distinct, cast, \
12
    between
13
from urlparse import urlparse
14
import requests
15
import json
16
import optparse
17
import urllib2
18
import base64
19
import urllib
15759 manish.sha 20
import logging
17228 manish.sha 21
from dtr.utils.utils import get_mongo_connection
15691 manish.sha 22
 
23
GCM_URL = "https://android.googleapis.com/gcm/send"
24
GOOGLE_API_KEY = "AIzaSyDw1qBnmxtnfR9NqBewryQ-yo3cG2ravGM"
17228 manish.sha 25
PENDING_PUSH_NOTIFICATION_URL = "http://45.33.50.227:3001/getPendingNotifications"
26
PUSH_NOTIFICATIONS_UPDATE_URL = "http://45.33.50.227:3001/updatePushNotification/?"
15691 manish.sha 27
headers = {'content-type':'application/json', "authorization":"key=" + GOOGLE_API_KEY}
28
aff_url_headers = { 
29
            'User-agent':'Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36',
30
            'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',      
31
            'Accept-Language' : 'en-US,en;q=0.8',                     
32
            'Accept-Charset' : 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
33
            'Connection':'keep-alive'
34
        }
35
 
36
db = MySQLdb.connect('localhost',"root","shop2020","dtr" )
37
cursor = db.cursor()
17228 manish.sha 38
userGcmRegIdMap = {}
39
campaignsMap = {}
15691 manish.sha 40
 
41
ALL_STORES_SQL = "select * from stores"
17228 manish.sha 42
GCM_REG_ID_SQL = "select x.user_id, x.gcm_regid from (select * from gcm_users where user_id in %s order by id desc) as x group by x.user_id"
43
CAMPAIGNS_SQL = "select * from notification_campaigns where id in %s order by id"
15691 manish.sha 44
 
17228 manish.sha 45
 
15691 manish.sha 46
cursor.execute(ALL_STORES_SQL)
47
result_stores = cursor.fetchall()
48
domainStoresMap = {}
49
for rec in result_stores:
50
    domainStoresMap[rec[2]] = rec
15759 manish.sha 51
 
52
logging.basicConfig(level=logging.DEBUG,
53
                    format='[%(levelname)s] (%(threadName)-10s) %(message)s',
54
                    )
15691 manish.sha 55
 
56
 
57
class NotificationRecord():
58
    pushNotificationId = None
59
    userId = None
60
    campaignId = None
61
    campaignName = None
62
    title = None
63
    message= None
64
    type = None
65
    url = None
66
    expiresAt = None
67
    notificationStatus = None
68
    notificationCreated = None
69
    gcmRegId = None
70
 
71
    def __init__(self,pushNotificationId, userId, campaignId, campaignName, title, message, type, url, expiresAt, notificationStatus, notificationCreated, gcmRegId):
72
        self.pushNotificationId = pushNotificationId
73
        self.userId = userId
74
        self.campaignId = campaignId
75
        self.campaignName = campaignName
76
        self.title = title
77
        self.message= message
78
        self.type = type
79
        self.url = url
80
        self.expiresAt = expiresAt
81
        self.notificationStatus = notificationStatus
82
        self.notificationCreated = notificationCreated
83
        self.gcmRegId = gcmRegId
84
 
85
 
86
class NotificationThread (threading.Thread):
87
    def __init__(self, threadID, name, recordsList):
88
        threading.Thread.__init__(self)
89
        self.threadID = threadID
90
        self.name = name
91
        self.recordsList = recordsList
92
    def run(self):
15759 manish.sha 93
        logging.debug('Starting')
15691 manish.sha 94
        handleCampaignRequest(self.name, self.recordsList)
15759 manish.sha 95
        logging.debug('Completed')
15691 manish.sha 96
 
97
def handleCampaignRequest(threadName, recordsList ):
98
    for record in recordsList:
17228 manish.sha 99
        campaignRecord = campaignsMap.get(record.get('notification_campaign_id'))
100
        notificationRecord = NotificationRecord(record.get('_id'), record.get('user_id'), record.get('notification_campaign_id'), campaignRecord[1], campaignRecord[2], campaignRecord[3], campaignRecord[4], campaignRecord[5], campaignRecord[7], campaignRecord[8], campaignRecord[9], userGcmRegIdMap.get(record.get('user_id')))
15691 manish.sha 101
        if notificationRecord.type=='url':
102
            parsed_uri = urlparse(notificationRecord.url)
103
            domain = '{uri.netloc}'.format(uri=parsed_uri)
15759 manish.sha 104
            logging.debug('Affiliate Domain:-'+str(domain))
105
            logging.debug('User Id:-'+str(notificationRecord.userId)+' And GCM Reg Id:- '+ str(notificationRecord.gcmRegId))
15691 manish.sha 106
            store = domainStoresMap.get(domain)
107
            if store is not None:
108
                url_params = { 'url' : notificationRecord.url,  'userId' : notificationRecord.userId, 'storeId' : store[0] }
109
                encoded_url_params = urllib.urlencode(url_params)
110
 
111
                DTR_API_BASIC_AUTH = base64.encodestring('%s:%s' % ("dtr", "dtr18Feb2015")).replace('\n', '')
112
 
113
                pushpostrequest = urllib2.Request('http://api.profittill.com/pushnotifications/generateAffiliateUrl', encoded_url_params, headers=aff_url_headers)
114
                pushpostrequest.add_header("Authorization", "Basic %s" % DTR_API_BASIC_AUTH)
115
                json_result =  json.loads(urllib2.urlopen(pushpostrequest).read())
116
                notificationRecord.url = json_result['url']
16294 manish.sha 117
                logging.debug('User Id:-'+str(notificationRecord.userId)+' Notification Url:- '+ str(notificationRecord.url))
16295 manish.sha 118
            else:
17490 manish.sha 119
                if '?user_id' not in notificationRecord.url:
18020 manish.sha 120
                    notificationRecord.url = notificationRecord.url.strip()+'?user_id='+str(notificationRecord.userId)
17490 manish.sha 121
                    logging.debug('User Id:-'+str(notificationRecord.userId)+' Notification Url:- '+ str(notificationRecord.url))
122
                else: 
123
                    logging.debug('User Id:-'+str(notificationRecord.userId)+' Notification Url:- '+ str(notificationRecord.url))
17235 manish.sha 124
        if notificationRecord.url is None or str(notificationRecord.url)=='':
125
            notificationRecord.url = 'http://api.profittill.com/deals?user_id='+str(notificationRecord.userId)
126
        data = {"message":notificationRecord.message,"cid":notificationRecord.campaignId,"title":notificationRecord.title,
18020 manish.sha 127
                "type":notificationRecord.type,"url":notificationRecord.url.strip(),"vibrate":1,"sound":1,"largeIcon":"large_icon",
17235 manish.sha 128
                "smallIcon":"small_icon","priority":"high","time_to_live":long(time.mktime(notificationRecord.expiresAt.timetuple()))-long(time.mktime(datetime.datetime.now().timetuple()))}
129
 
130
        post_data = {}
131
 
132
        post_data['data'] = data
133
        regIds = []
134
        regIds.append(notificationRecord.gcmRegId)
135
        post_data['registration_ids'] = regIds
136
 
137
        post_data_json = json.dumps(post_data)
138
        logging.debug('User Id:- '+str(notificationRecord.userId)+' Post Data Json :- '+str(post_data_json))
139
 
140
        response = requests.post(GCM_URL, data=post_data_json, headers=headers)
141
        logging.debug('User Id:- '+str(notificationRecord.userId)+' Response :-'+str(response.text))
142
        result = json.loads(response.text)
143
 
144
        if result["success"]:
18247 manas 145
            update_params = { 'user_id' : notificationRecord.userId,  'notification_campaign_id' : notificationRecord.campaignId, 'oldType':'pending', 'type' : 'sent', 'status':1, 'message':'success' }
17235 manish.sha 146
            encoded_update_params = urllib.urlencode(update_params)
147
            updateReq = urllib2.Request(PUSH_NOTIFICATIONS_UPDATE_URL+encoded_update_params)
148
            updateResponse = urllib2.urlopen(updateReq)
149
            response_str = updateResponse.read()
150
            logging.debug('User Id:- '+str(notificationRecord.userId)+' Update Response :-'+str(response_str))
151
        else:
18247 manas 152
            update_params = { 'user_id' : notificationRecord.userId,  'notification_campaign_id' : notificationRecord.campaignId, 'oldType':'pending', 'type' : 'sent', 'status':0, 'message':result["results"][0]["error"] }
17235 manish.sha 153
            encoded_update_params = urllib.urlencode(update_params)
154
            updateReq = urllib2.Request(PUSH_NOTIFICATIONS_UPDATE_URL+encoded_update_params)
155
            updateResponse = urllib2.urlopen(updateReq)
156
            response_str = updateResponse.read()
157
            logging.debug('User Id:- '+str(notificationRecord.userId)+' Update Response :-'+str(response_str))
15691 manish.sha 158
 
17235 manish.sha 159
            updateGcmUserSql = "update gcm_users set failurecount=failurecount+1 where gcm_regid='%s'"%(notificationRecord.gcmRegId)
160
            logging.debug('Update GCM User Query :-'+str(updateGcmUserSql))
161
            try:
162
                dtrdb = MySQLdb.connect('localhost',"root","shop2020","dtr" )
163
                cursor = dtrdb.cursor()
164
                cursor.execute(updateGcmUserSql)
165
                dtrdb.commit()
166
                session.commit()
167
                dtrdb.close()
168
            except:
169
                dtrdb.rollback()
170
                dtrdb.close()
15759 manish.sha 171
            #time.sleep(2)
15691 manish.sha 172
 
173
def chunks(l, n):
174
    """Yield successive n-sized chunks from l."""
175
    for i in xrange(0, len(l), n):
176
        yield l[i:i+n]
177
 
178
def main():
17228 manish.sha 179
    global userGcmRegIdMap
180
    global campaignsMap
15691 manish.sha 181
    parser = optparse.OptionParser()
182
    parser.add_option("-C", "--chunksize", dest="chunksize",
183
                      default="100",
184
                      type="int", help="The requsets a single thread handles",
185
                      metavar="CHUNKSIZE")
186
    (options, args) = parser.parse_args()
187
 
17228 manish.sha 188
 
189
    notificationListReq = urllib2.Request(PENDING_PUSH_NOTIFICATION_URL)
190
    notificationListResponse = urllib2.urlopen(notificationListReq)
191
    notificationListJson = json.loads(notificationListResponse.read())
192
 
193
    usersList =[]
194
    campaignIdList = []
195
 
196
    for notificationRec in notificationListJson:
197
        if notificationRec.get('user_id') not in usersList:
198
            usersList.append(notificationRec.get('user_id'))
199
        if notificationRec.get('notification_campaign_id') not in campaignIdList:
200
            campaignIdList.append(notificationRec.get('notification_campaign_id'))
201
 
202
    usersList.append(0)
203
    campaignIdList.append(0)
17235 manish.sha 204
    logging.debug('Starting Push Notification Job....'+str(datetime.datetime.now()))
15691 manish.sha 205
 
17229 manish.sha 206
    if len(usersList) >1 and len(campaignIdList)>1:
207
        cursor.execute(GCM_REG_ID_SQL%(str(tuple(usersList))))
208
        result_data = cursor.fetchall()
17228 manish.sha 209
 
17229 manish.sha 210
        for dataRec in result_data:
211
            userGcmRegIdMap[dataRec[0]] = dataRec[1]
15691 manish.sha 212
 
17229 manish.sha 213
        cursor.execute(CAMPAIGNS_SQL%(str(tuple(campaignIdList))))
214
        campaign_data = cursor.fetchall()
215
 
216
        for campaignRec in campaign_data:
217
            campaignsMap[campaignRec[0]] = campaignRec    
218
 
219
        count = 1
220
        if result_data:
221
            campaign_receivers_list = list(chunks(notificationListJson, options.chunksize))
222
            print len(campaign_receivers_list)
223
            for sublist in campaign_receivers_list:
224
                thread = NotificationThread(count, "Thread-"+str(count), sublist)
225
                thread.start()
226
                count = count +1
17235 manish.sha 227
 
228
    logging.debug('Stopping Push Notification Job....'+str(datetime.datetime.now()))
17229 manish.sha 229
 
15691 manish.sha 230
    db.close()
231
 
232
if __name__=='__main__':
233
    main()
234