Subversion Repositories SmartDukaan

Rev

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