Subversion Repositories SmartDukaan

Rev

Rev 19122 | Rev 19124 | Go to most recent revision | 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 elixir import *
8
from sqlalchemy.orm.exc import NoResultFound, MultipleResultsFound
9
from sqlalchemy.sql import func
10
from sqlalchemy.sql.expression import and_, or_, desc, not_, distinct, cast, \
11
    between
12
from urlparse import urlparse
13
from urlparse import parse_qs
14
import requests
15
import json
16
import optparse
17
import urllib2
18
import base64
19
import urllib
20
import logging
21
from dtr.utils.utils import get_mongo_connection, to_java_date
22
from datetime import datetime
23
 
24
GCM_URL = "https://android.googleapis.com/gcm/send"
25
GOOGLE_API_KEY = "AIzaSyDw1qBnmxtnfR9NqBewryQ-yo3cG2ravGM"
26
headers = {'content-type':'application/json', "authorization":"key=" + GOOGLE_API_KEY}
27
aff_url_headers = { 
28
            'User-agent':'Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36',
29
            'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',      
30
            'Accept-Language' : 'en-US,en;q=0.8',                     
31
            'Accept-Charset' : 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
32
            'Connection':'keep-alive'
33
        }
34
 
35
mongoHost = 'localhost' 
36
campaignUsersMap = {}
37
notificationCampaignsMap = {}
38
pendingNotificationEntryMap = {}
39
userGcmRegIdMap = {}
40
db = MySQLdb.connect('localhost',"root","shop2020","dtr" )
41
cursor = db.cursor()
42
 
43
ALL_STORES_SQL = "select * from stores"
19104 manish.sha 44
GCM_REG_ID_SQL1 = "select x.user_id, x.gcm_regid, x.id, x.androidid, x.created  from (select * from gcm_users where user_id in %s and androidid is not null order by id desc) as x group by x.user_id, x.gcm_regid, x.androidid"
45
GCM_REG_ID_SQL2 = "select x.user_id, x.gcm_regid, x.id, x.androidid, x.created  from (select * from gcm_users where user_id in %s and androidid is null order by id desc) as x group by x.user_id, x.gcm_regid"
46
 
19095 manish.sha 47
cursor.execute(ALL_STORES_SQL)
48
result_stores = cursor.fetchall()
49
domainStoresMap = {}
50
for rec in result_stores:
51
    domainStoresMap[rec[2]] = rec
52
 
53
logging.basicConfig(level=logging.DEBUG,
54
                    format='[%(levelname)s] (%(threadName)-10s) %(message)s',
55
                    )
56
 
57
class NotificationThread (threading.Thread):
58
    def __init__(self, threadID, name, recordsList):
59
        threading.Thread.__init__(self)
60
        self.threadID = threadID
61
        self.name = name
62
        self.recordsList = recordsList
63
    def run(self):
64
        logging.debug('Starting')
65
        handleCampaignRequest(self.name, self.recordsList)
66
        logging.debug('Completed')
67
 
68
def handleCampaignRequest(threadName, recordsList ):
69
    for record in recordsList:
19122 manish.sha 70
        userGcmRegIdDetails = userGcmRegIdMap.get(long(record.get('user_id')))
19095 manish.sha 71
        campaign = notificationCampaignsMap.get(record.get('notification_campaign_id')) 
72
        for gcm_id, detailsMap in userGcmRegIdDetails.items():
73
            result_url = ""
74
            if campaign.get('type')=='url':
75
                parsed_uri = urlparse(campaign.get('url'))
76
                domain = '{uri.netloc}'.format(uri=parsed_uri)
77
                logging.debug('Affiliate Domain:-'+str(domain))
78
                logging.debug('User Id:-'+str(record.get('user_id'))+' And GCM Reg Id:- '+ str(detailsMap.get('gcm_regid')))
79
                store = domainStoresMap.get(domain)
80
                if store is not None:
81
                    url_params = { 'url' : campaign.get('url'),  'userId' : record.get('user_id'), 'storeId' : store[0] }
82
                    encoded_url_params = urllib.urlencode(url_params)
83
                    DTR_API_BASIC_AUTH = base64.encodestring('%s:%s' % ("dtr", "dtr18Feb2015")).replace('\n', '')
84
 
85
                    pushpostrequest = urllib2.Request('http://api.profittill.com/pushnotifications/generateAffiliateUrl', encoded_url_params, headers=aff_url_headers)
86
                    pushpostrequest.add_header("Authorization", "Basic %s" % DTR_API_BASIC_AUTH)
87
                    json_result =  json.loads(urllib2.urlopen(pushpostrequest).read())
88
                    result_url = json_result['url']
89
                    logging.debug('User Id:-'+str(record.get('user_id'))+' Notification Url:- '+ str(result_url))
90
                else:
91
                    queryString = urlparse(campaign.get('url').strip()).query
92
                    parsed_url = parse_qs(queryString)
93
                    if not parsed_url.has_key('user_id'):
94
                        if len(queryString)>0:
95
                            result_url = campaign.get('url').strip()+'&user_id='+str(record.get('user_id'))
96
                            logging.debug('User Id:-'+str(record.get('user_id'))+' Notification Url:- '+ str(result_url))
97
                        else:
98
                            result_url = campaign.get('url').strip()+'?user_id='+str(record.get('user_id'))
99
                            logging.debug('User Id:-'+str(record.get('user_id'))+' Notification Url:- '+ str(result_url))
100
                    else:
101
                        logging.debug('User Id:-'+str(record.get('user_id'))+' Notification Url:- '+ str(record.get('user_id')))
102
            if campaign.get('url') is None or str(campaign.get('url'))=='':
103
                result_url = 'http://api.profittill.com/deals?user_id='+str(record.get('user_id'))
104
            data = {"message":campaign.get('message'),"cid":str(campaign.get('_id'))+"_"+str(record.get('_id')),"title":campaign.get('title'),
105
                    "type":campaign.get('type'),"url":result_url.strip(),"vibrate":1,"sound":1,"largeIcon":"large_icon",
19104 manish.sha 106
                    "smallIcon":"small_icon","priority":"high","time_to_live":long(campaign.get('expiresat'))-long(time.mktime(datetime.now().timetuple()))}
19095 manish.sha 107
 
108
            post_data = {}
109
 
110
            post_data['data'] = data
111
            regIds = []
112
            regIds.append(detailsMap.get('gcm_regid'))
113
            post_data['registration_ids'] = regIds
114
 
115
            post_data_json = json.dumps(post_data)
116
            logging.debug('User Id:- '+str(record.get('user_id'))+' Post Data Json :- '+str(post_data_json))
117
            response = requests.post(GCM_URL, data=post_data_json, headers=headers)
118
            logging.debug('User Id:- '+str(record.get('user_id'))+' GCM_ID:- '+str(gcm_id)+' Response :-'+str(response.text))
119
            result = json.loads(response.text)
120
            if result["success"]:
19122 manish.sha 121
                get_mongo_connection(host=mongoHost).User.pushnotifications.update({'_id':record.get('_id')},{"$set":{'message':'success','type':'sent','sent_timestamp':to_java_date(datetime.now())}})
19095 manish.sha 122
                logging.debug('User Id:- '+str(record.get('user_id'))+' GCM_ID:- '+str(gcm_id)+' Update Response :- Notification Success True')
123
            else:
19122 manish.sha 124
                get_mongo_connection(host=mongoHost).User.pushnotifications.update({'_id':record.get('_id')},{"$set":{'message':result["results"][0]["error"],'type':'failed','sent_timestamp':to_java_date(datetime.now())}})
19095 manish.sha 125
                logging.debug('User Id:- '+str(record.get('user_id'))+' GCM_ID:- '+str(gcm_id)+' Update Response :- Notification Fail True')
126
                updateGcmUserSql = "update gcm_users set failurecount=failurecount+1 where gcm_regid='%s'"%(detailsMap.get('gcm_regid'))
127
                logging.debug('Update GCM User Query :-'+str(updateGcmUserSql))
128
                try:
129
                    dtrdb = MySQLdb.connect('localhost',"root","shop2020","dtr" )
130
                    cursor = dtrdb.cursor()
131
                    cursor.execute(updateGcmUserSql)
132
                    dtrdb.commit()
133
                    session.commit()
134
                    dtrdb.close()
135
                except:
136
                    dtrdb.rollback()
137
                    dtrdb.close()
138
 
139
def chunks(l, n):
140
    """Yield successive n-sized chunks from l."""
141
    for i in xrange(0, len(l), n):
142
        yield l[i:i+n]
143
 
144
class __PushNotification:
145
    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):
146
        self.notification_campaign_id = notification_campaign_id
147
        self.user_id = user_id
148
        self.message = message
149
        self.type = type
150
        self.sms_type = sms_type
151
        self.sms_id = sms_id
152
        self.android_id = android_id
153
        self.pushed_by = pushed_by
154
        self.sent_timestamp = sent_timestamp
155
        self.receive_timestamp = receive_timestamp
156
        self.open_timestamp = open_timestamp
157
        self.sms_timestamp = sms_timestamp
158
        self.gcm_id = gcm_id
159
        self.created_timestamp = created_timestamp
160
        self.gcm_expired = gcm_expired 
161
 
162
def getPendingCampaigns():
163
    campaigns = list(get_mongo_connection(host=mongoHost).User.notificationcampaigns.find({'notification_processed':0,'expiresat':{'$gte':to_java_date(datetime.now())}}))
164
    return campaigns
165
 
166
def populateCampaignsMap(pendingCampaigns):
167
    global campaignUsersMap
168
    global notificationCampaignsMap
169
    for campaign in pendingCampaigns:
19104 manish.sha 170
        cursor.execute(str(campaign['sql']))
19095 manish.sha 171
        user_records = cursor.fetchall()
172
        userids = []
173
        for record in user_records:
19115 manish.sha 174
            if record[0] not in userids:
175
                userids.append(str(record[0]))
19095 manish.sha 176
        campaignUsersMap[campaign['_id']]=userids
177
        notificationCampaignsMap[campaign['_id']] = campaign
178
 
179
def insertPushNotificationEntriesToSent():
180
    global userGcmRegIdMap
181
    for userList in campaignUsersMap.values():
19122 manish.sha 182
        logging.debug("GCM_REG_SQL_1:- "+GCM_REG_ID_SQL1%(str(tuple(userList))))
19104 manish.sha 183
        cursor.execute(GCM_REG_ID_SQL1%(str(tuple(userList))))
19095 manish.sha 184
        result_data = cursor.fetchall()
185
 
19104 manish.sha 186
        if result_data and len(result_data)>0:
19122 manish.sha 187
            user_list = []
188
            for userId in userList:
189
                user_list.append(userId)
190
 
19104 manish.sha 191
            for dataRec in result_data:
19122 manish.sha 192
                if dataRec[0] in user_list:
193
                    user_list.remove(str(dataRec[0]))
19104 manish.sha 194
                if userGcmRegIdMap.has_key(dataRec[0]):
195
                    detailMap = {}
196
                    gcmRegIdMap = userGcmRegIdMap.get(dataRec[0])
197
                    detailMap['gcm_regid'] = dataRec[1]
198
                    if dataRec[3] is not None:
199
                        detailMap['android_id'] = dataRec[3]
200
                    gcmRegIdMap[dataRec[2]]= detailMap
201
                    userGcmRegIdMap[dataRec[0]] = gcmRegIdMap
202
                else:
203
                    gcmRegIdMap = {}
204
                    detailMap = {}
205
                    detailMap['gcm_regid'] = dataRec[1]
206
                    if dataRec[3] is not None:
207
                        detailMap['android_id'] = dataRec[3]
208
                    gcmRegIdMap[dataRec[2]]= detailMap
209
                    userGcmRegIdMap[dataRec[0]] = gcmRegIdMap
19122 manish.sha 210
 
19123 manish.sha 211
            logging.debug("Old Users.."+str(user_list)) 
19122 manish.sha 212
            logging.debug("GCM_REG_SQL_2:- "+GCM_REG_ID_SQL2%(str(tuple(user_list))))       
213
            cursor.execute(GCM_REG_ID_SQL2%(str(tuple(user_list))))
19104 manish.sha 214
            result_data = cursor.fetchall()
215
            for dataRec in result_data:
216
                if userGcmRegIdMap.has_key(dataRec[0]):
217
                    detailMap = {}
218
                    gcmRegIdMap = userGcmRegIdMap.get(dataRec[0])
219
                    detailMap['gcm_regid'] = dataRec[1]
220
                    if dataRec[3] is not None:
221
                        detailMap['android_id'] = dataRec[3]
222
                    gcmRegIdMap[dataRec[2]]= detailMap
223
                    userGcmRegIdMap[dataRec[0]] = gcmRegIdMap
224
                else:
225
                    gcmRegIdMap = {}
226
                    detailMap = {}
227
                    detailMap['gcm_regid'] = dataRec[1]
228
                    if dataRec[3] is not None:
229
                        detailMap['android_id'] = dataRec[3]
230
                    gcmRegIdMap[dataRec[2]]= detailMap
231
                    userGcmRegIdMap[dataRec[0]] = gcmRegIdMap
232
        else:
19122 manish.sha 233
            logging.debug("GCM_REG_SQL_2:- "+GCM_REG_ID_SQL2%(str(tuple(userList))))
234
            cursor.execute(GCM_REG_ID_SQL2%(str(tuple(userList))))   
19104 manish.sha 235
            result_data = cursor.fetchall()
236
            for dataRec in result_data:
237
                if userGcmRegIdMap.has_key(dataRec[0]):
238
                    detailMap = {}
239
                    gcmRegIdMap = userGcmRegIdMap.get(dataRec[0])
240
                    detailMap['gcm_regid'] = dataRec[1]
241
                    if dataRec[3] is not None:
242
                        detailMap['android_id'] = dataRec[3]
243
                    gcmRegIdMap[dataRec[2]]= detailMap
244
                    userGcmRegIdMap[dataRec[0]] = gcmRegIdMap
245
                else:
246
                    gcmRegIdMap = {}
247
                    detailMap = {}
248
                    detailMap['gcm_regid'] = dataRec[1]
249
                    if dataRec[3] is not None:
250
                        detailMap['android_id'] = dataRec[3]
251
                    gcmRegIdMap[dataRec[2]]= detailMap
19117 manish.sha 252
                    userGcmRegIdMap[dataRec[0]] = gcmRegIdMap   
253
 
254
    logging.debug("CampaignUsersMap"+str(campaignUsersMap)) 
19095 manish.sha 255
 
256
    for campaignId, userList in campaignUsersMap.items():
257
        for userId in userList:
19122 manish.sha 258
            gcmRegIdMap = userGcmRegIdMap.get(long(userId))
19095 manish.sha 259
            if gcmRegIdMap is None:
260
                gcmRegIdMap = {}
261
            for gcm_id, details in gcmRegIdMap.items():
262
                android_id = None
19122 manish.sha 263
                logging.debug("User Id:- "+str(userId)+" ..User Details:- "+str(details))
19095 manish.sha 264
                if details.has_key('android_id'):
265
                    android_id = details['android_id']
266
                pushNotificationObj = __PushNotification(campaignId, userId, None, 'pending', \
19112 manish.sha 267
                                    None, None, android_id, "php", None, None, None, None, gcm_id, to_java_date(datetime.now()),0)
19122 manish.sha 268
                get_mongo_connection(host=mongoHost).User.pushnotifications.insert(pushNotificationObj.__dict__)
19095 manish.sha 269
 
270
def populatePendingNotificationEntriesToBeSent():
271
    global pendingNotificationEntryMap
19122 manish.sha 272
    pendingNotificationEntries = list(get_mongo_connection(host=mongoHost).User.pushnotifications.find({'type':'pending'}))
19095 manish.sha 273
    for entry in pendingNotificationEntries:
274
        if pendingNotificationEntryMap.has_key(entry['notification_campaign_id']):
275
            entries = pendingNotificationEntryMap.get(entry['notification_campaign_id'])
276
            entries.append(entry)
277
            pendingNotificationEntryMap[entry['notification_campaign_id']] = entries
278
        else:
279
            entries = []
280
            entries.append(entry)
281
            pendingNotificationEntryMap[entry['notification_campaign_id']] = entries
282
 
283
def initiateNotificationThreadProcess(chunkSize):
284
    count = 1
19104 manish.sha 285
    logging.debug('Starting Push Notification Job....'+str(datetime.now()))
19095 manish.sha 286
    for entries in pendingNotificationEntryMap.values():
287
        campaign_receivers_list = list(chunks(entries, chunkSize))
288
        print len(campaign_receivers_list)
289
        for sublist in campaign_receivers_list:
290
            thread = NotificationThread(count, "Thread-"+str(count), sublist)
291
            thread.start()
292
            count = count +1
19104 manish.sha 293
    logging.debug('Stopping Push Notification Job....'+str(datetime.now()))
19095 manish.sha 294
 
19104 manish.sha 295
def markNotificationCampaignsProcessed():
296
    for campaign in notificationCampaignsMap.values():
297
        logging.debug('Notification Campaign....'+str(campaign.get('notification_id'))+"...Marked Processed. "+str(datetime.now()))
298
        get_mongo_connection(host=mongoHost).User.notificationcampaigns.update({'_id':campaign.get('_id')},{"$set":{'notification_processed':1}})     
299
 
19095 manish.sha 300
def main():
301
    global mongoHost
302
    parser = optparse.OptionParser()
303
    parser.add_option("-C", "--chunksize", dest="chunksize",
304
                      default="100",
305
                      type="int", help="The requsets a single thread handles",
306
                      metavar="CHUNKSIZE")
307
    parser.add_option("-M", "--mongo_host", dest="mongo_host",
308
                      default="localhost",
309
                      type="str", help="The requsets a single thread handles",
310
                      metavar="MONGOHOST")
311
    (options, args) = parser.parse_args()
312
    mongoHost = options.mongo_host
313
    pendingCampaigns = getPendingCampaigns()
314
    populateCampaignsMap(pendingCampaigns)
315
    insertPushNotificationEntriesToSent()
316
    populatePendingNotificationEntriesToBeSent()
317
    initiateNotificationThreadProcess(options.chunksize)
19104 manish.sha 318
    markNotificationCampaignsProcessed()
319
 
320
    db.close()
19095 manish.sha 321
 
322
if __name__=='__main__':
323
    main()
324