Subversion Repositories SmartDukaan

Rev

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