Subversion Repositories SmartDukaan

Rev

Rev 19104 | Rev 19113 | 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:
70
        userGcmRegIdDetails = userGcmRegIdMap.get(record.get('user_id'))
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"]:
121
                get_mongo_connection(host=mongoHost).User.pushnotificationsnew.update({'_id':record.get('_id')},{"$set":{'message':'success','type':'sent','sent_timestamp':to_java_date(datetime.now())}})
122
                logging.debug('User Id:- '+str(record.get('user_id'))+' GCM_ID:- '+str(gcm_id)+' Update Response :- Notification Success True')
123
            else:
124
                get_mongo_connection(host=mongoHost).User.pushnotificationsnew.update({'_id':record.get('_id')},{"$set":{'message':result["results"][0]["error"],'type':'failed','sent_timestamp':to_java_date(datetime.now())}})
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:
174
            if long(record[0]) not in userids:
175
                userids.append(long(record[0]))
176
        campaignUsersMap[campaign['_id']]=userids
177
        notificationCampaignsMap[campaign['_id']] = campaign
178
 
179
def insertPushNotificationEntriesToSent():
180
    global userGcmRegIdMap
181
    for userList in campaignUsersMap.values():
19104 manish.sha 182
        cursor.execute(GCM_REG_ID_SQL1%(str(tuple(userList))))
19095 manish.sha 183
        result_data = cursor.fetchall()
184
 
19104 manish.sha 185
        if result_data and len(result_data)>0:
186
            for dataRec in result_data:
187
                if dataRec[0] in userList:
188
                    userList.remove(long(dataRec[0]))
189
                if userGcmRegIdMap.has_key(dataRec[0]):
190
                    detailMap = {}
191
                    gcmRegIdMap = userGcmRegIdMap.get(dataRec[0])
192
                    detailMap['gcm_regid'] = dataRec[1]
193
                    if dataRec[3] is not None:
194
                        detailMap['android_id'] = dataRec[3]
195
                    gcmRegIdMap[dataRec[2]]= detailMap
196
                    userGcmRegIdMap[dataRec[0]] = gcmRegIdMap
197
                else:
198
                    gcmRegIdMap = {}
199
                    detailMap = {}
200
                    detailMap['gcm_regid'] = dataRec[1]
201
                    if dataRec[3] is not None:
202
                        detailMap['android_id'] = dataRec[3]
203
                    gcmRegIdMap[dataRec[2]]= detailMap
204
                    userGcmRegIdMap[dataRec[0]] = gcmRegIdMap
205
 
206
            cursor.execute(GCM_REG_ID_SQL2%(str(tuple(userList))))
207
            result_data = cursor.fetchall()
208
            for dataRec in result_data:
209
                if userGcmRegIdMap.has_key(dataRec[0]):
210
                    detailMap = {}
211
                    gcmRegIdMap = userGcmRegIdMap.get(dataRec[0])
212
                    detailMap['gcm_regid'] = dataRec[1]
213
                    if dataRec[3] is not None:
214
                        detailMap['android_id'] = dataRec[3]
215
                    gcmRegIdMap[dataRec[2]]= detailMap
216
                    userGcmRegIdMap[dataRec[0]] = gcmRegIdMap
217
                else:
218
                    gcmRegIdMap = {}
219
                    detailMap = {}
220
                    detailMap['gcm_regid'] = dataRec[1]
221
                    if dataRec[3] is not None:
222
                        detailMap['android_id'] = dataRec[3]
223
                    gcmRegIdMap[dataRec[2]]= detailMap
224
                    userGcmRegIdMap[dataRec[0]] = gcmRegIdMap
225
        else:
226
            cursor.execute(GCM_REG_ID_SQL2%(str(tuple(userList))))
227
            result_data = cursor.fetchall()
228
            for dataRec in result_data:
229
                if userGcmRegIdMap.has_key(dataRec[0]):
230
                    detailMap = {}
231
                    gcmRegIdMap = userGcmRegIdMap.get(dataRec[0])
232
                    detailMap['gcm_regid'] = dataRec[1]
233
                    if dataRec[3] is not None:
234
                        detailMap['android_id'] = dataRec[3]
235
                    gcmRegIdMap[dataRec[2]]= detailMap
236
                    userGcmRegIdMap[dataRec[0]] = gcmRegIdMap
237
                else:
238
                    gcmRegIdMap = {}
239
                    detailMap = {}
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    
19095 manish.sha 245
 
246
    for campaignId, userList in campaignUsersMap.items():
247
        for userId in userList:
248
            gcmRegIdMap = userGcmRegIdMap.get(userId)
249
            if gcmRegIdMap is None:
250
                gcmRegIdMap = {}
251
            for gcm_id, details in gcmRegIdMap.items():
252
                android_id = None
253
                if details.has_key('android_id'):
254
                    android_id = details['android_id']
255
                pushNotificationObj = __PushNotification(campaignId, userId, None, 'pending', \
19112 manish.sha 256
                                    None, None, android_id, "php", None, None, None, None, gcm_id, to_java_date(datetime.now()),0)
19095 manish.sha 257
                get_mongo_connection(host=mongoHost).User.pushnotificationsnew.insert(pushNotificationObj.__dict__)
258
 
259
def populatePendingNotificationEntriesToBeSent():
260
    global pendingNotificationEntryMap
261
    pendingNotificationEntries = list(get_mongo_connection(host=mongoHost).User.pushnotificationsnew.find({'type':'pending'}))
262
    for entry in pendingNotificationEntries:
263
        if pendingNotificationEntryMap.has_key(entry['notification_campaign_id']):
264
            entries = pendingNotificationEntryMap.get(entry['notification_campaign_id'])
265
            entries.append(entry)
266
            pendingNotificationEntryMap[entry['notification_campaign_id']] = entries
267
        else:
268
            entries = []
269
            entries.append(entry)
270
            pendingNotificationEntryMap[entry['notification_campaign_id']] = entries
271
 
272
def initiateNotificationThreadProcess(chunkSize):
273
    count = 1
19104 manish.sha 274
    logging.debug('Starting Push Notification Job....'+str(datetime.now()))
19095 manish.sha 275
    for entries in pendingNotificationEntryMap.values():
276
        campaign_receivers_list = list(chunks(entries, chunkSize))
277
        print len(campaign_receivers_list)
278
        for sublist in campaign_receivers_list:
279
            thread = NotificationThread(count, "Thread-"+str(count), sublist)
280
            thread.start()
281
            count = count +1
19104 manish.sha 282
    logging.debug('Stopping Push Notification Job....'+str(datetime.now()))
19095 manish.sha 283
 
19104 manish.sha 284
def markNotificationCampaignsProcessed():
285
    for campaign in notificationCampaignsMap.values():
286
        logging.debug('Notification Campaign....'+str(campaign.get('notification_id'))+"...Marked Processed. "+str(datetime.now()))
287
        get_mongo_connection(host=mongoHost).User.notificationcampaigns.update({'_id':campaign.get('_id')},{"$set":{'notification_processed':1}})     
288
 
19095 manish.sha 289
def main():
290
    global mongoHost
291
    parser = optparse.OptionParser()
292
    parser.add_option("-C", "--chunksize", dest="chunksize",
293
                      default="100",
294
                      type="int", help="The requsets a single thread handles",
295
                      metavar="CHUNKSIZE")
296
    parser.add_option("-M", "--mongo_host", dest="mongo_host",
297
                      default="localhost",
298
                      type="str", help="The requsets a single thread handles",
299
                      metavar="MONGOHOST")
300
    (options, args) = parser.parse_args()
301
    mongoHost = options.mongo_host
302
    pendingCampaigns = getPendingCampaigns()
303
    populateCampaignsMap(pendingCampaigns)
304
    insertPushNotificationEntriesToSent()
305
    populatePendingNotificationEntriesToBeSent()
306
    initiateNotificationThreadProcess(options.chunksize)
19104 manish.sha 307
    markNotificationCampaignsProcessed()
308
 
309
    db.close()
19095 manish.sha 310
 
311
if __name__=='__main__':
312
    main()
313