Subversion Repositories SmartDukaan

Rev

Rev 19246 | Rev 19655 | 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"
19218 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"
19232 manish.sha 45
GCM_REG_ID_SQL2 = "select x.user_id, x.gcm_regid, x.id, x.androidid, x.created, x.imeinumber  from (select * from gcm_users where user_id in (%s) and androidid is null and imeinumber is not null order by id desc) as x group by x.user_id, x.imeinumber"
19104 manish.sha 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')))
19246 manish.sha 71
        campaign = notificationCampaignsMap.get(long(record.get('notification_campaign_id'))) 
19134 manish.sha 72
        gcm_id = record.get('gcm_id')
73
        detailsMap = userGcmRegIdDetails.get(gcm_id)
74
        result_url = ""
75
        if campaign.get('type')=='url':
76
            parsed_uri = urlparse(campaign.get('url'))
77
            domain = '{uri.netloc}'.format(uri=parsed_uri)
78
            logging.debug('Affiliate Domain:-'+str(domain))
79
            logging.debug('User Id:-'+str(record.get('user_id'))+' And GCM Reg Id:- '+ str(detailsMap.get('gcm_regid')))
80
            store = domainStoresMap.get(domain)
81
            if store is not None:
82
                url_params = { 'url' : campaign.get('url'),  'userId' : record.get('user_id'), 'storeId' : store[0] }
83
                encoded_url_params = urllib.urlencode(url_params)
84
                DTR_API_BASIC_AUTH = base64.encodestring('%s:%s' % ("dtr", "dtr18Feb2015")).replace('\n', '')
85
 
86
                pushpostrequest = urllib2.Request('http://api.profittill.com/pushnotifications/generateAffiliateUrl', encoded_url_params, headers=aff_url_headers)
87
                pushpostrequest.add_header("Authorization", "Basic %s" % DTR_API_BASIC_AUTH)
88
                json_result =  json.loads(urllib2.urlopen(pushpostrequest).read())
89
                result_url = json_result['url']
90
                logging.debug('User Id:-'+str(record.get('user_id'))+' Notification Url:- '+ str(result_url))
91
            else:
92
                queryString = urlparse(campaign.get('url').strip()).query
93
                parsed_url = parse_qs(queryString)
94
                if not parsed_url.has_key('user_id'):
95
                    if len(queryString)>0:
96
                        result_url = campaign.get('url').strip()+'&user_id='+str(record.get('user_id'))
97
                        logging.debug('User Id:-'+str(record.get('user_id'))+' Notification Url:- '+ str(result_url))
98
                    else:
99
                        result_url = campaign.get('url').strip()+'?user_id='+str(record.get('user_id'))
100
                        logging.debug('User Id:-'+str(record.get('user_id'))+' Notification Url:- '+ str(result_url))
19095 manish.sha 101
                else:
19134 manish.sha 102
                    logging.debug('User Id:-'+str(record.get('user_id'))+' Notification Url:- '+ str(record.get('user_id')))
103
        if campaign.get('url') is None or str(campaign.get('url'))=='':
104
            result_url = 'http://api.profittill.com/deals?user_id='+str(record.get('user_id'))
105
        data = {"message":campaign.get('message'),"cid":str(campaign.get('_id'))+"_"+str(record.get('_id')),"title":campaign.get('title'),
106
                "type":campaign.get('type'),"url":result_url.strip(),"vibrate":1,"sound":1,"largeIcon":"large_icon",
107
                "smallIcon":"small_icon","priority":"high","time_to_live":long(campaign.get('expiresat'))-long(time.mktime(datetime.now().timetuple()))}
108
 
109
        post_data = {}
110
 
111
        post_data['data'] = data
112
        regIds = []
113
        regIds.append(detailsMap.get('gcm_regid'))
114
        post_data['registration_ids'] = regIds
115
 
116
        post_data_json = json.dumps(post_data)
117
        logging.debug('User Id:- '+str(record.get('user_id'))+' Post Data Json :- '+str(post_data_json))
118
        response = requests.post(GCM_URL, data=post_data_json, headers=headers)
119
        logging.debug('User Id:- '+str(record.get('user_id'))+' GCM_ID:- '+str(gcm_id)+' Response :-'+str(response.text))
120
        result = json.loads(response.text)
121
        if result["success"]:
122
            get_mongo_connection(host=mongoHost).User.pushnotifications.update({'_id':record.get('_id')},{"$set":{'message':'success','type':'sent','sent_timestamp':to_java_date(datetime.now())}})
123
            logging.debug('User Id:- '+str(record.get('user_id'))+' GCM_ID:- '+str(gcm_id)+' Update Response :- Notification Success True')
124
        else:
125
            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())}})
126
            logging.debug('User Id:- '+str(record.get('user_id'))+' GCM_ID:- '+str(gcm_id)+' Update Response :- Notification Fail True')
127
            updateGcmUserSql = "update gcm_users set failurecount=failurecount+1 where gcm_regid='%s'"%(detailsMap.get('gcm_regid'))
128
            logging.debug('Update GCM User Query :-'+str(updateGcmUserSql))
129
            try:
130
                dtrdb = MySQLdb.connect('localhost',"root","shop2020","dtr" )
131
                cursor = dtrdb.cursor()
132
                cursor.execute(updateGcmUserSql)
133
                dtrdb.commit()
134
                session.commit()
135
                dtrdb.close()
136
            except:
137
                dtrdb.rollback()
138
                dtrdb.close()
19095 manish.sha 139
 
140
def chunks(l, n):
141
    """Yield successive n-sized chunks from l."""
142
    for i in xrange(0, len(l), n):
143
        yield l[i:i+n]
144
 
145
class __PushNotification:
19217 manish.sha 146
    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):
19095 manish.sha 147
        self.notification_campaign_id = notification_campaign_id
148
        self.user_id = user_id
149
        self.message = message
150
        self.type = type
151
        self.sms_type = sms_type
152
        self.sms_id = sms_id
153
        self.android_id = android_id
154
        self.pushed_by = pushed_by
155
        self.sent_timestamp = sent_timestamp
156
        self.receive_timestamp = receive_timestamp
157
        self.open_timestamp = open_timestamp
158
        self.sms_timestamp = sms_timestamp
159
        self.gcm_id = gcm_id
160
        self.created_timestamp = created_timestamp
19217 manish.sha 161
        self.gcm_expired = gcm_expired
162
        self.notification_accounted = notification_accounted
19095 manish.sha 163
 
164
def getPendingCampaigns():
165
    campaigns = list(get_mongo_connection(host=mongoHost).User.notificationcampaigns.find({'notification_processed':0,'expiresat':{'$gte':to_java_date(datetime.now())}}))
166
    return campaigns
167
 
168
def populateCampaignsMap(pendingCampaigns):
169
    global campaignUsersMap
170
    global notificationCampaignsMap
171
    for campaign in pendingCampaigns:
19104 manish.sha 172
        cursor.execute(str(campaign['sql']))
19095 manish.sha 173
        user_records = cursor.fetchall()
174
        userids = []
175
        for record in user_records:
19133 manish.sha 176
            if str(record[0]) not in userids:
19115 manish.sha 177
                userids.append(str(record[0]))
19246 manish.sha 178
        campaignUsersMap[long(campaign['_id'])]=userids
179
        notificationCampaignsMap[long(campaign['_id'])] = campaign
19095 manish.sha 180
 
181
def insertPushNotificationEntriesToSent():
182
    global userGcmRegIdMap
19369 manish.sha 183
    for campaignId, userList in campaignUsersMap.items():
184
        logging.debug("CampaignId:- "+str(campaignId))
185
        if len(userList)==0:
186
            continue
19218 manish.sha 187
        logging.debug("GCM_REG_SQL_1:- "+GCM_REG_ID_SQL1%(",".join(map(str,userList))))
188
        cursor.execute(GCM_REG_ID_SQL1%(",".join(map(str,userList))))
19095 manish.sha 189
        result_data = cursor.fetchall()
190
 
19104 manish.sha 191
        if result_data and len(result_data)>0:
19122 manish.sha 192
            user_list = []
193
            for userId in userList:
194
                user_list.append(userId)
195
 
19104 manish.sha 196
            for dataRec in result_data:
19217 manish.sha 197
                '''
19124 manish.sha 198
                if str(dataRec[0]) in user_list:
19122 manish.sha 199
                    user_list.remove(str(dataRec[0]))
19217 manish.sha 200
                '''
19104 manish.sha 201
                if userGcmRegIdMap.has_key(dataRec[0]):
202
                    detailMap = {}
203
                    gcmRegIdMap = userGcmRegIdMap.get(dataRec[0])
204
                    detailMap['gcm_regid'] = dataRec[1]
205
                    if dataRec[3] is not None:
206
                        detailMap['android_id'] = dataRec[3]
207
                    gcmRegIdMap[dataRec[2]]= detailMap
208
                    userGcmRegIdMap[dataRec[0]] = gcmRegIdMap
209
                else:
210
                    gcmRegIdMap = {}
211
                    detailMap = {}
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
19122 manish.sha 217
 
19125 manish.sha 218
            logging.debug("Old Users.."+str(user_list))
19218 manish.sha 219
            logging.debug("GCM_REG_SQL_2:- "+GCM_REG_ID_SQL2%(",".join(map(str,user_list))))       
220
            cursor.execute(GCM_REG_ID_SQL2%(",".join(map(str,user_list))))
19104 manish.sha 221
            result_data = cursor.fetchall()
222
            for dataRec in result_data:
223
                if userGcmRegIdMap.has_key(dataRec[0]):
224
                    detailMap = {}
225
                    gcmRegIdMap = userGcmRegIdMap.get(dataRec[0])
226
                    detailMap['gcm_regid'] = dataRec[1]
227
                    if dataRec[3] is not None:
228
                        detailMap['android_id'] = dataRec[3]
229
                    gcmRegIdMap[dataRec[2]]= detailMap
230
                    userGcmRegIdMap[dataRec[0]] = gcmRegIdMap
231
                else:
232
                    gcmRegIdMap = {}
233
                    detailMap = {}
234
                    detailMap['gcm_regid'] = dataRec[1]
235
                    if dataRec[3] is not None:
236
                        detailMap['android_id'] = dataRec[3]
237
                    gcmRegIdMap[dataRec[2]]= detailMap
238
                    userGcmRegIdMap[dataRec[0]] = gcmRegIdMap
239
        else:
19218 manish.sha 240
            logging.debug("GCM_REG_SQL_2:- "+GCM_REG_ID_SQL2%(",".join(map(str,userList))))
241
            cursor.execute(GCM_REG_ID_SQL2%(",".join(map(str,userList))))   
19104 manish.sha 242
            result_data = cursor.fetchall()
243
            for dataRec in result_data:
244
                if userGcmRegIdMap.has_key(dataRec[0]):
245
                    detailMap = {}
246
                    gcmRegIdMap = userGcmRegIdMap.get(dataRec[0])
247
                    detailMap['gcm_regid'] = dataRec[1]
248
                    if dataRec[3] is not None:
249
                        detailMap['android_id'] = dataRec[3]
250
                    gcmRegIdMap[dataRec[2]]= detailMap
251
                    userGcmRegIdMap[dataRec[0]] = gcmRegIdMap
252
                else:
253
                    gcmRegIdMap = {}
254
                    detailMap = {}
255
                    detailMap['gcm_regid'] = dataRec[1]
256
                    if dataRec[3] is not None:
257
                        detailMap['android_id'] = dataRec[3]
258
                    gcmRegIdMap[dataRec[2]]= detailMap
19117 manish.sha 259
                    userGcmRegIdMap[dataRec[0]] = gcmRegIdMap   
260
 
261
    logging.debug("CampaignUsersMap"+str(campaignUsersMap)) 
19095 manish.sha 262
 
263
    for campaignId, userList in campaignUsersMap.items():
264
        for userId in userList:
19122 manish.sha 265
            gcmRegIdMap = userGcmRegIdMap.get(long(userId))
19095 manish.sha 266
            if gcmRegIdMap is None:
267
                gcmRegIdMap = {}
268
            for gcm_id, details in gcmRegIdMap.items():
269
                android_id = None
19122 manish.sha 270
                logging.debug("User Id:- "+str(userId)+" ..User Details:- "+str(details))
19095 manish.sha 271
                if details.has_key('android_id'):
272
                    android_id = details['android_id']
19246 manish.sha 273
                pushNotificationObj = __PushNotification(long(campaignId), long(userId), None, 'pending', \
19217 manish.sha 274
                                    None, None, android_id, "php", None, None, None, None, gcm_id, to_java_date(datetime.now()),0,0)
19122 manish.sha 275
                get_mongo_connection(host=mongoHost).User.pushnotifications.insert(pushNotificationObj.__dict__)
19095 manish.sha 276
 
277
def populatePendingNotificationEntriesToBeSent():
278
    global pendingNotificationEntryMap
19122 manish.sha 279
    pendingNotificationEntries = list(get_mongo_connection(host=mongoHost).User.pushnotifications.find({'type':'pending'}))
19095 manish.sha 280
    for entry in pendingNotificationEntries:
281
        if pendingNotificationEntryMap.has_key(entry['notification_campaign_id']):
282
            entries = pendingNotificationEntryMap.get(entry['notification_campaign_id'])
283
            entries.append(entry)
284
            pendingNotificationEntryMap[entry['notification_campaign_id']] = entries
285
        else:
286
            entries = []
287
            entries.append(entry)
288
            pendingNotificationEntryMap[entry['notification_campaign_id']] = entries
289
 
290
def initiateNotificationThreadProcess(chunkSize):
291
    count = 1
19104 manish.sha 292
    logging.debug('Starting Push Notification Job....'+str(datetime.now()))
19095 manish.sha 293
    for entries in pendingNotificationEntryMap.values():
294
        campaign_receivers_list = list(chunks(entries, chunkSize))
295
        print len(campaign_receivers_list)
296
        for sublist in campaign_receivers_list:
297
            thread = NotificationThread(count, "Thread-"+str(count), sublist)
298
            thread.start()
299
            count = count +1
19104 manish.sha 300
    logging.debug('Stopping Push Notification Job....'+str(datetime.now()))
19095 manish.sha 301
 
19104 manish.sha 302
def markNotificationCampaignsProcessed():
303
    for campaign in notificationCampaignsMap.values():
19125 manish.sha 304
        logging.debug('Notification Campaign....'+str(campaign.get('_id'))+"...Marked Processed. "+str(datetime.now()))
19104 manish.sha 305
        get_mongo_connection(host=mongoHost).User.notificationcampaigns.update({'_id':campaign.get('_id')},{"$set":{'notification_processed':1}})     
306
 
19095 manish.sha 307
def main():
308
    global mongoHost
309
    parser = optparse.OptionParser()
310
    parser.add_option("-C", "--chunksize", dest="chunksize",
311
                      default="100",
312
                      type="int", help="The requsets a single thread handles",
313
                      metavar="CHUNKSIZE")
314
    parser.add_option("-M", "--mongo_host", dest="mongo_host",
315
                      default="localhost",
316
                      type="str", help="The requsets a single thread handles",
317
                      metavar="MONGOHOST")
318
    (options, args) = parser.parse_args()
319
    mongoHost = options.mongo_host
320
    pendingCampaigns = getPendingCampaigns()
321
    populateCampaignsMap(pendingCampaigns)
322
    insertPushNotificationEntriesToSent()
323
    populatePendingNotificationEntriesToBeSent()
324
    initiateNotificationThreadProcess(options.chunksize)
19104 manish.sha 325
    markNotificationCampaignsProcessed()
326
 
327
    db.close()
19095 manish.sha 328
 
329
if __name__=='__main__':
330
    main()
331