Subversion Repositories SmartDukaan

Rev

Rev 24396 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
19095 manish.sha 1
#!/usr/bin/python
2
 
3
import threading
4
import time
5
 
6
import MySQLdb
7
from urlparse import urlparse
8
from urlparse import parse_qs
9
import requests
10
import json
11
import optparse
12
import urllib2
13
import base64
14
import urllib
15
import logging
16
from dtr.utils.utils import get_mongo_connection, to_java_date
17
from datetime import datetime
19655 manish.sha 18
import traceback
19095 manish.sha 19
 
20173 kshitij.so 20
parser = optparse.OptionParser()
21
parser.add_option("-C", "--chunksize", dest="chunksize",
22
                  default="100",
23
                  type="int", help="The requsets a single thread handles",
24
                  metavar="CHUNKSIZE")
25
parser.add_option("-M", "--mongoHost", dest="mongoHost",
26
                  default="localhost",
27
                  type="str", help="The requsets a single thread handles",
28
                  metavar="MONGOHOST")
29
parser.add_option("-m", "--mysqlHost", dest="mysqlHost",
24397 amit.gupta 30
                  default="127.0.0.1",
20173 kshitij.so 31
                  type="str", help="The requsets a single thread handles",
32
                  metavar="MONGOHOST")
33
 
34
(options, args) = parser.parse_args()
35
 
19095 manish.sha 36
GCM_URL = "https://android.googleapis.com/gcm/send"
24396 amit.gupta 37
FCM_URL = "https://fcm.googleapis.com/fcm/send"
20173 kshitij.so 38
GOOGLE_API_KEY = "AIzaSyBGL29sWCKm8OweP62ywrfv4jv4VIN8u0o"
24396 amit.gupta 39
FCM_API_KEY = "AAAASAjNcn4:APA91bG6fWRIgYJI0L9gCjP5ynaXz2hJHYKtD9dfH7Depdv31Nd9APJwhx-OPkAJ1WSz4BGNYG8lHThLFSjDGFxIwUZv241YcAJEGDLgt86mxq9FXJe-yBRu-S0_ZwHqmX-QaVKl5F_A"
40
headers_gcm = {'content-type':'application/json', "authorization":"key=" + GOOGLE_API_KEY}
41
headers_fcm = {'content-type':'application/json', "authorization":"key=" + FCM_API_KEY}
19095 manish.sha 42
aff_url_headers = { 
43
            'User-agent':'Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36',
44
            'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',      
45
            'Accept-Language' : 'en-US,en;q=0.8',                     
46
            'Accept-Charset' : 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
47
            'Connection':'keep-alive'
48
        }
49
 
20173 kshitij.so 50
pendingNotificationSet = {'_id':1,'user_id':1,'gcm_id':1,'notification_campaign_id':1}
24396 amit.gupta 51
pendingCampaignSet = {'_id':1,'name':1,'title':1,'message':1,'type':1,'url':1,'sql':1,'expiresat':1,'image':1} 
20173 kshitij.so 52
 
53
pendingNotificationEntryMap = {}
19095 manish.sha 54
campaignUsersMap = {}
55
notificationCampaignsMap = {}
56
userGcmRegIdMap = {}
20173 kshitij.so 57
gcmIdGcmRegIdMap = {}
58
domainStoresMap = {}
59
failedGcm = []
60
 
61
 
24395 amit.gupta 62
db = MySQLdb.connect(options.mysqlHost,"root","shop2020","dtr" )
19095 manish.sha 63
cursor = db.cursor()
64
 
65
ALL_STORES_SQL = "select * from stores"
24396 amit.gupta 66
GCM_REG_ID_SQL1 = "select x.user_id, x.gcm_regid, x.id, x.androidid, x.created, x.notification_type from (select gc.* from gcm_users gc join users u on gc.user_id=u.id where gc.user_id in (%s) and gc.androidid is not null and u.activated=1 and gc.failurecount < 2 order by gc.id desc) as x group by x.user_id, x.gcm_regid, x.androidid"
67
GCM_REG_ID_SQL2 = "select x.user_id, x.gcm_regid, x.id, x.androidid, x.created, x.imeinumber,x.notification_type from (select gc.* from gcm_users gc join users u on u.id=gc.user_id where gc.user_id in (%s) and gc.androidid is null and gc.imeinumber is not null and gc.failurecount < 2 and u.activated=1 order by id desc) as x group by x.user_id, x.imeinumber"
68
FETCH_GCM_REG_SQL = "select id, gcm_regid, notification_type from gcm_users where id in (%s)"
19104 manish.sha 69
 
19095 manish.sha 70
cursor.execute(ALL_STORES_SQL)
71
result_stores = cursor.fetchall()
72
domainStoresMap = {}
73
for rec in result_stores:
74
    domainStoresMap[rec[2]] = rec
75
 
76
logging.basicConfig(level=logging.DEBUG,
77
                    format='[%(levelname)s] (%(threadName)-10s) %(message)s',
78
                    )
79
 
20173 kshitij.so 80
class __PushNotification:
81
    def __init__(self, notification_campaign_id, user_id, message, type, sms_type, sms_id, android_id, pushed_by, sent_timestamp, receive_timestamp, open_timestamp, sms_timestamp, gcm_id, created_timestamp, gcm_expired, notification_accounted):
82
        self.notification_campaign_id = notification_campaign_id
83
        self.user_id = user_id
84
        self.message = message
85
        self.type = type
86
        self.sms_type = sms_type
87
        self.sms_id = sms_id
88
        self.android_id = android_id
89
        self.pushed_by = pushed_by
90
        self.sent_timestamp = sent_timestamp
91
        self.receive_timestamp = receive_timestamp
92
        self.open_timestamp = open_timestamp
93
        self.sms_timestamp = sms_timestamp
94
        self.gcm_id = gcm_id
95
        self.created_timestamp = created_timestamp
96
        self.gcm_expired = gcm_expired
97
        self.notification_accounted = notification_accounted
98
 
99
 
100
 
101
def populatePendingNotificationEntriesToBeSent():
102
    global pendingNotificationEntryMap
103
    toRefetchGcmId = []
104
    offset = 0
24396 amit.gupta 105
    old_campaigns = []
20173 kshitij.so 106
    while(True):
107
        pendingNotificationEntries = list(get_mongo_connection(host=options.mongoHost).User.pushnotifications.find({'type':'pending'}, pendingNotificationSet).skip(offset).limit(10000))
108
        if not pendingNotificationEntries:
109
            break
110
        for entry in pendingNotificationEntries:
24396 amit.gupta 111
            try:
112
                gcm_regid = gcmIdGcmRegIdMap.get(entry.get('gcm_id'))[0]
113
            except:
114
                gcm_regid = None
20173 kshitij.so 115
            if gcm_regid is None:
116
                toRefetchGcmId.append(entry.get('gcm_id'))
24396 amit.gupta 117
            if not notificationCampaignsMap.has_key(long(entry['notification_campaign_id'])):
118
                old_campaigns.append(long(entry['notification_campaign_id']))
20173 kshitij.so 119
            if pendingNotificationEntryMap.has_key(entry['notification_campaign_id']):
120
                entries = pendingNotificationEntryMap.get(entry['notification_campaign_id'])
121
                entries.append(entry)
122
                pendingNotificationEntryMap[entry['notification_campaign_id']] = entries
123
            else:
124
                entries = []
125
                entries.append(entry)
126
                pendingNotificationEntryMap[entry['notification_campaign_id']] = entries
127
        offset = offset + 10000
128
    logging.debug("FETCH_GCM_REG_SQL:- "+FETCH_GCM_REG_SQL%(",".join(map(str,toRefetchGcmId))))
129
    if not toRefetchGcmId:
130
        print "No gcm to refetch"
131
        return
132
    cursor.execute(FETCH_GCM_REG_SQL%(",".join(map(str,toRefetchGcmId))))
133
    result_data = cursor.fetchall()
134
    if result_data:
135
        for data in result_data:
24396 amit.gupta 136
            gcmIdGcmRegIdMap[data[0]] = [data[1],data[2]]
137
 
138
    if old_campaigns:
139
        print "yes, old campaigns exist"
140
        campaigns = list(get_mongo_connection(host=options.mongoHost).User.notificationcampaigns.find({'_id':{"$in":old_campaigns}},pendingCampaignSet))
141
        for campaign in campaigns:
142
            notificationCampaignsMap[long(campaign['_id'])] = campaign
20173 kshitij.so 143
 
144
 
145
 
146
def populateCampaignsMap(pendingCampaigns):
147
    global campaignUsersMap
148
    global notificationCampaignsMap
149
    for campaign in pendingCampaigns:
150
        cursor.execute(str(campaign['sql']))
151
        user_records = cursor.fetchall()
152
        userids = []
153
        for record in user_records:
154
            if str(record[0]) not in userids:
155
                userids.append(str(record[0]))
156
        campaignUsersMap[long(campaign['_id'])]=userids
157
        notificationCampaignsMap[long(campaign['_id'])] = campaign
158
 
159
def getPendingCampaigns():
160
    campaigns = list(get_mongo_connection(host=options.mongoHost).User.notificationcampaigns.find({'notification_processed':0,'expiresat':{'$gte':to_java_date(datetime.now())}},pendingCampaignSet))
161
    return campaigns
162
 
163
def insertPushNotificationEntriesToSent():
164
    global userGcmRegIdMap
165
    global gcmIdGcmRegIdMap
166
    for campaignId, user_list in campaignUsersMap.items():
167
        if len(user_list)==0:
168
            continue
169
        logging.debug("GCM_REG_SQL_1:- "+GCM_REG_ID_SQL1%(",".join(map(str,user_list))))
170
        cursor.execute(GCM_REG_ID_SQL1%(",".join(map(str,user_list))))
171
        result_data = cursor.fetchall()
172
 
173
        if result_data and len(result_data)>0:
174
 
175
            for dataRec in result_data:
176
 
24396 amit.gupta 177
                gcmIdGcmRegIdMap[dataRec[2]] = [dataRec[1], dataRec[5]]
20173 kshitij.so 178
 
179
                if userGcmRegIdMap.has_key(dataRec[0]):
180
                    gcmRegIdMap = userGcmRegIdMap.get(dataRec[0])
181
                    gcmRegIdMap[dataRec[2]]= {'gcm_regid':dataRec[1],'android_id':dataRec[3]}
182
                    userGcmRegIdMap[dataRec[0]] = gcmRegIdMap
183
                else:
184
                    userGcmRegIdMap[dataRec[0]] = {dataRec[2]:{'gcm_regid':dataRec[1],'android_id':dataRec[3]}}
24396 amit.gupta 185
 
20173 kshitij.so 186
        logging.debug("GCM_REG_SQL_2:- "+GCM_REG_ID_SQL2%(",".join(map(str,user_list))))       
187
        cursor.execute(GCM_REG_ID_SQL2%(",".join(map(str,user_list))))
188
        result_data = cursor.fetchall()
189
        for dataRec in result_data:
190
 
24396 amit.gupta 191
            gcmIdGcmRegIdMap[dataRec[2]] = [dataRec[1], dataRec[6]]
20173 kshitij.so 192
 
193
            if userGcmRegIdMap.has_key(dataRec[0]):
194
                gcmRegIdMap = userGcmRegIdMap.get(dataRec[0])
195
                gcmRegIdMap[dataRec[2]]= {'gcm_regid':dataRec[1],'android_id':dataRec[3]}
196
                userGcmRegIdMap[dataRec[0]] = gcmRegIdMap
197
            else:
198
                userGcmRegIdMap[dataRec[0]] = {dataRec[2]:{'gcm_regid':dataRec[1],'android_id':None}}
199
 
200
 
201
    for campaignId, userList in campaignUsersMap.items():
202
        bulkArrayPushNotificationObj = []
203
        bulkCount = 0
204
        for userId in userList:
205
            gcmRegIdMap = userGcmRegIdMap.get(long(userId))
206
            if gcmRegIdMap is None:
207
                logging.debug("No value exist in gcm map for user_id"+str(userId))
208
                continue
209
            for gcm_id, details in gcmRegIdMap.items():
210
                android_id = None
211
                if details.has_key('android_id'):
212
                    android_id = details['android_id']
213
                pushNotificationObj = __PushNotification(long(campaignId), long(userId), None, 'pending', \
214
                                    None, None, android_id, "php", None, None, None, None, gcm_id, to_java_date(datetime.now()),0,0)
215
                bulkArrayPushNotificationObj.append(pushNotificationObj.__dict__)
216
                bulkCount = bulkCount + 1
217
            if bulkCount >= 10000:
218
                get_mongo_connection(host=options.mongoHost).User.pushnotifications.insert(bulkArrayPushNotificationObj)
219
                bulkCount = 0
220
                bulkArrayPushNotificationObj = []
221
 
222
        if bulkArrayPushNotificationObj:
223
            get_mongo_connection(host=options.mongoHost).User.pushnotifications.insert(bulkArrayPushNotificationObj)
224
 
225
def initiateNotificationThreadProcess(chunkSize):
226
    count = 1
227
    logging.debug('Starting Push Notification Job....'+str(datetime.now()))
228
    for entries in pendingNotificationEntryMap.values():
229
        campaign_receivers_list = list(chunks(entries, chunkSize))
230
        for sublist in campaign_receivers_list:
231
            thread = NotificationThread(count, "Thread-"+str(count), sublist)
232
            thread.start()
233
            thread.join()
234
            count = count +1
235
    logging.debug('Stopping Push Notification Job....'+str(datetime.now()))
236
 
19095 manish.sha 237
class NotificationThread (threading.Thread):
238
    def __init__(self, threadID, name, recordsList):
239
        threading.Thread.__init__(self)
240
        self.threadID = threadID
241
        self.name = name
242
        self.recordsList = recordsList
20173 kshitij.so 243
 
19095 manish.sha 244
    def run(self):
245
        logging.debug('Starting')
246
        handleCampaignRequest(self.name, self.recordsList)
247
        logging.debug('Completed')
248
 
249
def handleCampaignRequest(threadName, recordsList ):
20173 kshitij.so 250
    global failedGcm
19095 manish.sha 251
    for record in recordsList:
19655 manish.sha 252
        try:
20173 kshitij.so 253
            #userGcmRegIdDetails = userGcmRegIdMap.get(long(record.get('user_id')))
19655 manish.sha 254
            campaign = notificationCampaignsMap.get(long(record.get('notification_campaign_id'))) 
255
            gcm_id = record.get('gcm_id')
24396 amit.gupta 256
            gcm_regid = gcmIdGcmRegIdMap.get(gcm_id)[0]
20173 kshitij.so 257
            if gcm_regid is None:
258
                print "Ideally should never raise"
259
                raise
19655 manish.sha 260
        except:
261
            logging.debug('Error while getting GCM Details for User Id:- '+ str(record.get('user_id'))+" and Notification Id:- "+str(record.get('notification_campaign_id')))
262
            traceback.print_exc() 
263
            continue
19134 manish.sha 264
        result_url = ""
265
        if campaign.get('type')=='url':
266
            parsed_uri = urlparse(campaign.get('url'))
267
            domain = '{uri.netloc}'.format(uri=parsed_uri)
268
            store = domainStoresMap.get(domain)
269
            if store is not None:
270
                url_params = { 'url' : campaign.get('url'),  'userId' : record.get('user_id'), 'storeId' : store[0] }
271
                encoded_url_params = urllib.urlencode(url_params)
272
                DTR_API_BASIC_AUTH = base64.encodestring('%s:%s' % ("dtr", "dtr18Feb2015")).replace('\n', '')
273
 
274
                pushpostrequest = urllib2.Request('http://api.profittill.com/pushnotifications/generateAffiliateUrl', encoded_url_params, headers=aff_url_headers)
275
                pushpostrequest.add_header("Authorization", "Basic %s" % DTR_API_BASIC_AUTH)
276
                json_result =  json.loads(urllib2.urlopen(pushpostrequest).read())
277
                result_url = json_result['url']
278
            else:
279
                queryString = urlparse(campaign.get('url').strip()).query
280
                parsed_url = parse_qs(queryString)
281
                if not parsed_url.has_key('user_id'):
282
                    if len(queryString)>0:
283
                        result_url = campaign.get('url').strip()+'&user_id='+str(record.get('user_id'))
284
                    else:
285
                        result_url = campaign.get('url').strip()+'?user_id='+str(record.get('user_id'))
19095 manish.sha 286
                else:
20173 kshitij.so 287
                    result_url = campaign.get('url').strip()
19134 manish.sha 288
        if campaign.get('url') is None or str(campaign.get('url'))=='':
289
            result_url = 'http://api.profittill.com/deals?user_id='+str(record.get('user_id'))
290
        data = {"message":campaign.get('message'),"cid":str(campaign.get('_id'))+"_"+str(record.get('_id')),"title":campaign.get('title'),
291
                "type":campaign.get('type'),"url":result_url.strip(),"vibrate":1,"sound":1,"largeIcon":"large_icon",
24396 amit.gupta 292
                "smallIcon":"small_icon","priority":"high","time_to_live":long(campaign.get('expiresat'))-long(time.mktime(datetime.now().timetuple())),"image":campaign.get("image")}
19134 manish.sha 293
 
294
        post_data = {}
295
 
296
        post_data['data'] = data
24396 amit.gupta 297
 
298
        if gcmIdGcmRegIdMap.get(gcm_id)[1] == 'gcm':
299
 
300
            regIds = []
301
            regIds.append(gcm_regid)
302
            post_data['registration_ids'] = regIds
303
 
304
            post_data_json = json.dumps(post_data)
305
            logging.debug('User Id:- '+str(record.get('user_id'))+' Post Data Json :- '+str(post_data_json))
306
            response = requests.post(GCM_URL, data=post_data_json, headers=headers_gcm)
307
 
308
        else:
309
 
310
            post_data['to'] = gcm_regid
311
            post_data['priority'] = 'high'
312
            post_data['sound'] = 'default'
313
            post_data['time_to_live'] = 2419200 
314
            post_data_json = json.dumps(post_data)
315
            logging.debug('User Id:- '+str(record.get('user_id'))+' Post Data Json :- '+str(post_data_json))
316
            response = requests.post(FCM_URL, data=post_data_json, headers=headers_fcm)
317
 
19134 manish.sha 318
        logging.debug('User Id:- '+str(record.get('user_id'))+' GCM_ID:- '+str(gcm_id)+' Response :-'+str(response.text))
319
        result = json.loads(response.text)
320
        if result["success"]:
20173 kshitij.so 321
            get_mongo_connection(host=options.mongoHost).User.pushnotifications.update({'_id':record.get('_id')},{"$set":{'message':'success','type':'sent','sent_timestamp':to_java_date(datetime.now())}})
19134 manish.sha 322
        else:
20173 kshitij.so 323
            get_mongo_connection(host=options.mongoHost).User.pushnotifications.update({'_id':record.get('_id')},{"$set":{'message':result["results"][0]["error"],'type':'failed','sent_timestamp':to_java_date(datetime.now())}})
324
            failedGcm.append(gcm_id)
325
#             updateGcmUserSql = "update gcm_users set failurecount=failurecount+1 where gcm_regid='%s'"%(gcm_regid)
326
#             logging.debug('Update GCM User Query :-'+str(updateGcmUserSql))
327
#             try:
328
#                 dtrdb = MySQLdb.connect('localhost',"root","shop2020","dtr" )
329
#                 cursor = dtrdb.cursor()
330
#                 cursor.execute(updateGcmUserSql)
331
#                 dtrdb.commit()
332
#                 session.commit()
333
#                 dtrdb.close()
334
#             except:
335
#                 dtrdb.rollback()
336
#                 dtrdb.close()
19095 manish.sha 337
 
338
def chunks(l, n):
339
    """Yield successive n-sized chunks from l."""
340
    for i in xrange(0, len(l), n):
341
        yield l[i:i+n]
342
 
19104 manish.sha 343
def markNotificationCampaignsProcessed():
344
    for campaign in notificationCampaignsMap.values():
19125 manish.sha 345
        logging.debug('Notification Campaign....'+str(campaign.get('_id'))+"...Marked Processed. "+str(datetime.now()))
20173 kshitij.so 346
        get_mongo_connection(host=options.mongoHost).User.notificationcampaigns.update({'_id':campaign.get('_id')},{"$set":{'notification_processed':1}})
347
 
348
def updateFailedGcm():
349
    updateGcmUserSql = "update gcm_users set failurecount=failurecount+1 where id in (%s)"
350
    logging.debug("updateGcmUserSql:- "+updateGcmUserSql%(",".join(map(str,failedGcm))))
351
    if not failedGcm:
352
        return
353
    cursor.execute(updateGcmUserSql%(",".join(map(str,failedGcm))))
19104 manish.sha 354
 
20173 kshitij.so 355
    try:
356
        db.commit()
357
    except:
358
        traceback.print_exc()
359
        db.rollback()
360
 
361
 
19095 manish.sha 362
def main():
20173 kshitij.so 363
    try:
364
        pendingCampaigns = getPendingCampaigns()
365
        populateCampaignsMap(pendingCampaigns)
366
        insertPushNotificationEntriesToSent()
367
        markNotificationCampaignsProcessed()
368
        populatePendingNotificationEntriesToBeSent()
369
        initiateNotificationThreadProcess(options.chunksize)
370
        updateFailedGcm()
371
    except:
372
        traceback.print_exc()
373
    finally:
374
        db.close()
19095 manish.sha 375
 
20173 kshitij.so 376
 
377
if __name__ == '__main__':
19095 manish.sha 378
    main()