Subversion Repositories SmartDukaan

Rev

Rev 18486 | Rev 19066 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
15691 manish.sha 1
#!/usr/bin/python
2
 
3
import threading
4
import time
16386 manish.sha 5
import datetime
15691 manish.sha 6
 
7
import MySQLdb
8
from elixir import *
9
from sqlalchemy.orm.exc import NoResultFound, MultipleResultsFound
10
from sqlalchemy.sql import func
11
from sqlalchemy.sql.expression import and_, or_, desc, not_, distinct, cast, \
12
    between
13
from urlparse import urlparse
18486 manish.sha 14
from urlparse import parse_qs
15691 manish.sha 15
import requests
16
import json
17
import optparse
18
import urllib2
19
import base64
20
import urllib
15759 manish.sha 21
import logging
17228 manish.sha 22
from dtr.utils.utils import get_mongo_connection
15691 manish.sha 23
 
24
GCM_URL = "https://android.googleapis.com/gcm/send"
25
GOOGLE_API_KEY = "AIzaSyDw1qBnmxtnfR9NqBewryQ-yo3cG2ravGM"
17228 manish.sha 26
PENDING_PUSH_NOTIFICATION_URL = "http://45.33.50.227:3001/getPendingNotifications"
27
PUSH_NOTIFICATIONS_UPDATE_URL = "http://45.33.50.227:3001/updatePushNotification/?"
19065 manish.sha 28
PUSH_NOTIFICATIONS_ADD_URL = "http://45.33.50.227:3001/addPushNotification"
15691 manish.sha 29
headers = {'content-type':'application/json', "authorization":"key=" + GOOGLE_API_KEY}
30
aff_url_headers = { 
31
            'User-agent':'Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36',
32
            'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',      
33
            'Accept-Language' : 'en-US,en;q=0.8',                     
34
            'Accept-Charset' : 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
35
            'Connection':'keep-alive'
36
        }
37
 
38
db = MySQLdb.connect('localhost',"root","shop2020","dtr" )
39
cursor = db.cursor()
17228 manish.sha 40
userGcmRegIdMap = {}
41
campaignsMap = {}
15691 manish.sha 42
 
43
ALL_STORES_SQL = "select * from stores"
19065 manish.sha 44
GCM_REG_ID_SQL = "select x.user_id, x.gcm_regid, x.imeinumber, x.created from (select * from gcm_users where user_id in %s and imeinumber is not null order by id desc) as x group by x.user_id, x.imeinumber"
17228 manish.sha 45
CAMPAIGNS_SQL = "select * from notification_campaigns where id in %s order by id"
15691 manish.sha 46
 
17228 manish.sha 47
 
15691 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
15759 manish.sha 53
 
54
logging.basicConfig(level=logging.DEBUG,
55
                    format='[%(levelname)s] (%(threadName)-10s) %(message)s',
56
                    )
15691 manish.sha 57
 
58
 
59
class NotificationRecord():
60
    pushNotificationId = None
61
    userId = None
62
    campaignId = None
63
    campaignName = None
64
    title = None
65
    message= None
66
    type = None
67
    url = None
68
    expiresAt = None
69
    notificationStatus = None
70
    notificationCreated = None
71
    gcmRegId = None
19065 manish.sha 72
    imeinumber = None
15691 manish.sha 73
 
19065 manish.sha 74
    def __init__(self,pushNotificationId, userId, campaignId, campaignName, title, message, type, url, expiresAt, notificationStatus, notificationCreated, gcmRegId, imeinumber):
15691 manish.sha 75
        self.pushNotificationId = pushNotificationId
76
        self.userId = userId
77
        self.campaignId = campaignId
78
        self.campaignName = campaignName
79
        self.title = title
80
        self.message= message
81
        self.type = type
82
        self.url = url
83
        self.expiresAt = expiresAt
84
        self.notificationStatus = notificationStatus
85
        self.notificationCreated = notificationCreated
86
        self.gcmRegId = gcmRegId
19065 manish.sha 87
        self.imeinumber = imeinumber
15691 manish.sha 88
 
89
 
90
class NotificationThread (threading.Thread):
91
    def __init__(self, threadID, name, recordsList):
92
        threading.Thread.__init__(self)
93
        self.threadID = threadID
94
        self.name = name
95
        self.recordsList = recordsList
96
    def run(self):
15759 manish.sha 97
        logging.debug('Starting')
15691 manish.sha 98
        handleCampaignRequest(self.name, self.recordsList)
15759 manish.sha 99
        logging.debug('Completed')
15691 manish.sha 100
 
101
def handleCampaignRequest(threadName, recordsList ):
102
    for record in recordsList:
17228 manish.sha 103
        campaignRecord = campaignsMap.get(record.get('notification_campaign_id'))
19065 manish.sha 104
        gcmRegIdsMap = userGcmRegIdMap.get(record.get('user_id'))
105
        successMarked = False
106
        if gcmRegIdsMap is None:
107
            gcmRegIdsMap = {}
108
        for imeiNumber, gcmRegId in gcmRegIdsMap.items():
109
            notificationRecord = NotificationRecord(record.get('_id'), record.get('user_id'), record.get('notification_campaign_id'), campaignRecord[1], campaignRecord[2], campaignRecord[3], campaignRecord[4], campaignRecord[5], campaignRecord[7], campaignRecord[8], campaignRecord[9], gcmRegId, imeiNumber)
110
            if notificationRecord.type=='url':
111
                parsed_uri = urlparse(notificationRecord.url)
112
                domain = '{uri.netloc}'.format(uri=parsed_uri)
113
                logging.debug('Affiliate Domain:-'+str(domain))
114
                logging.debug('User Id:-'+str(notificationRecord.userId)+' And GCM Reg Id:- '+ str(notificationRecord.gcmRegId))
115
                store = domainStoresMap.get(domain)
116
                if store is not None:
117
                    url_params = { 'url' : notificationRecord.url,  'userId' : notificationRecord.userId, 'storeId' : store[0] }
118
                    encoded_url_params = urllib.urlencode(url_params)
119
 
120
                    DTR_API_BASIC_AUTH = base64.encodestring('%s:%s' % ("dtr", "dtr18Feb2015")).replace('\n', '')
121
 
122
                    pushpostrequest = urllib2.Request('http://api.profittill.com/pushnotifications/generateAffiliateUrl', encoded_url_params, headers=aff_url_headers)
123
                    pushpostrequest.add_header("Authorization", "Basic %s" % DTR_API_BASIC_AUTH)
124
                    json_result =  json.loads(urllib2.urlopen(pushpostrequest).read())
125
                    notificationRecord.url = json_result['url']
126
                    logging.debug('User Id:-'+str(notificationRecord.userId)+' Notification Url:- '+ str(notificationRecord.url))
127
                else:
128
                    queryString = urlparse(notificationRecord.url.strip()).query
129
                    parsed_url = parse_qs(queryString)
130
                    if not parsed_url.has_key('user_id'):
131
                        if len(queryString)>0:
132
                            notificationRecord.url = notificationRecord.url.strip()+'&user_id='+str(notificationRecord.userId)
133
                            logging.debug('User Id:-'+str(notificationRecord.userId)+' Notification Url:- '+ str(notificationRecord.url))
134
                        else:
135
                            notificationRecord.url = notificationRecord.url.strip()+'?user_id='+str(notificationRecord.userId)
136
                            logging.debug('User Id:-'+str(notificationRecord.userId)+' Notification Url:- '+ str(notificationRecord.url))
18486 manish.sha 137
                    else:
138
                        logging.debug('User Id:-'+str(notificationRecord.userId)+' Notification Url:- '+ str(notificationRecord.url))
19065 manish.sha 139
 
140
            if notificationRecord.url is None or str(notificationRecord.url)=='':
141
                notificationRecord.url = 'http://api.profittill.com/deals?user_id='+str(notificationRecord.userId)
142
            data = {"message":notificationRecord.message,"cid":str(notificationRecord.campaignId)+"_"+str(notificationRecord.imeinumber),"title":notificationRecord.title,
143
                    "type":notificationRecord.type,"url":notificationRecord.url.strip(),"vibrate":1,"sound":1,"largeIcon":"large_icon",
144
                    "smallIcon":"small_icon","priority":"high","time_to_live":long(time.mktime(notificationRecord.expiresAt.timetuple()))-long(time.mktime(datetime.datetime.now().timetuple()))}
145
 
146
            post_data = {}
147
 
148
            post_data['data'] = data
149
            regIds = []
150
            regIds.append(notificationRecord.gcmRegId)
151
            post_data['registration_ids'] = regIds
152
 
153
            post_data_json = json.dumps(post_data)
154
            logging.debug('User Id:- '+str(notificationRecord.userId)+' Post Data Json :- '+str(post_data_json))
155
 
156
 
157
            if not successMarked:
158
                response = requests.post(GCM_URL, data=post_data_json, headers=headers)
159
                logging.debug('User Id:- '+str(notificationRecord.userId)+' Imeinumber:- '+str(notificationRecord.imeinumber)+' Response :-'+str(response.text))
160
                result = json.loads(response.text)
161
                if result["success"]:
162
                    update_params = { 'user_id' : notificationRecord.userId,  'notification_campaign_id' : notificationRecord.campaignId, 'oldType':'pending', 'type' : 'sent', 'status':1, 'message':'success', 'imei':str(notificationRecord.imeinumber) }
163
                    encoded_update_params = urllib.urlencode(update_params)
164
                    updateReq = urllib2.Request(PUSH_NOTIFICATIONS_UPDATE_URL+encoded_update_params)
165
                    updateResponse = urllib2.urlopen(updateReq)
166
                    response_str = updateResponse.read()
167
                    successMarked = True
168
                    logging.debug('User Id:- '+str(notificationRecord.userId)+' Imeinumber:- '+str(notificationRecord.imeinumber)+' Update Response :-'+str(response_str))
18486 manish.sha 169
                else:
19065 manish.sha 170
                    update_params = { 'user_id' : notificationRecord.userId,  'notification_campaign_id' : notificationRecord.campaignId, 'oldType':'pending', 'type' : 'sent', 'status':0, 'message':result["results"][0]["error"], 'imei':str(notificationRecord.imeinumber) }
171
                    encoded_update_params = urllib.urlencode(update_params)
172
                    updateReq = urllib2.Request(PUSH_NOTIFICATIONS_UPDATE_URL+encoded_update_params)
173
                    updateResponse = urllib2.urlopen(updateReq)
174
                    response_str = updateResponse.read()
175
                    logging.debug('User Id:- '+str(notificationRecord.userId)+' Imeinumber:- '+str(notificationRecord.imeinumber)+' Update Response :-'+str(response_str))
176
 
177
                    updateGcmUserSql = "update gcm_users set failurecount=failurecount+1 where gcm_regid='%s'"%(notificationRecord.gcmRegId)
178
                    logging.debug('Update GCM User Query :-'+str(updateGcmUserSql))
179
                    try:
180
                        dtrdb = MySQLdb.connect('localhost',"root","shop2020","dtr" )
181
                        cursor = dtrdb.cursor()
182
                        cursor.execute(updateGcmUserSql)
183
                        dtrdb.commit()
184
                        session.commit()
185
                        dtrdb.close()
186
                    except:
187
                        dtrdb.rollback()
188
                        dtrdb.close()
15691 manish.sha 189
 
19065 manish.sha 190
            else:
191
                payloadList = []
192
                payload = {}
193
                payload["user_id"]= notificationRecord.userId
194
                payload["type"]="pending"
195
                payload["notification_campaign_id"]= notificationRecord.campaignId
196
                payload["status"]=0
197
                payload["message"]=""
198
                payload["imei"]=""
199
 
200
                payloadList.append(payload)
201
                logging.debug('User Id:- '+str(notificationRecord.userId)+' Adding Pending Record for Notification Id :-'+str(notificationRecord.campaignId) +" and Imei Number:- " +str(notificationRecord.imeinumber))
202
 
203
                jsonObj = json.dumps([dict(pn) for pn in payloadList])
204
                pushpostrequest = urllib2.Request(PUSH_NOTIFICATIONS_ADD_URL)
205
                pushpostrequest.add_header('Content-Type', 'application/json')
206
                response = urllib2.urlopen(pushpostrequest, jsonObj).read()
207
 
208
                response = requests.post(GCM_URL, data=post_data_json, headers=headers)
209
                logging.debug('User Id:- '+str(notificationRecord.userId)+' Imeinumber:- '+str(notificationRecord.imeinumber)+' Response :-'+str(response.text))
210
                result = json.loads(response.text)
211
 
212
                if result["success"]:                    
213
                    update_params = { 'user_id' : notificationRecord.userId,  'notification_campaign_id' : notificationRecord.campaignId, 'type' : 'sent', 'status':1, 'message':'success', 'imei':str(notificationRecord.imeinumber) }
214
                    encoded_update_params = urllib.urlencode(update_params)
215
                    updateReq = urllib2.Request(PUSH_NOTIFICATIONS_UPDATE_URL+encoded_update_params)
216
                    updateResponse = urllib2.urlopen(updateReq)
217
                    response_str = updateResponse.read()
218
                    successMarked = True
219
                    logging.debug('User Id:- '+str(notificationRecord.userId)+' Imeinumber:- '+str(notificationRecord.imeinumber)+' Update Response :-'+str(response_str))
220
 
221
                else:
222
                    update_params = { 'user_id' : notificationRecord.userId,  'notification_campaign_id' : notificationRecord.campaignId, 'type' : 'sent', 'status':0, 'message':result["results"][0]["error"], 'imei':str(notificationRecord.imeinumber) }
223
                    encoded_update_params = urllib.urlencode(update_params)
224
                    updateReq = urllib2.Request(PUSH_NOTIFICATIONS_UPDATE_URL+encoded_update_params)
225
                    updateResponse = urllib2.urlopen(updateReq)
226
                    response_str = updateResponse.read()
227
                    logging.debug('User Id:- '+str(notificationRecord.userId)+' Imeinumber:- '+str(notificationRecord.imeinumber)+' Update Response :-'+str(response_str))
228
 
229
                    updateGcmUserSql = "update gcm_users set failurecount=failurecount+1 where gcm_regid='%s'"%(notificationRecord.gcmRegId)
230
                    logging.debug('Update GCM User Query :-'+str(updateGcmUserSql))
231
                    try:
232
                        dtrdb = MySQLdb.connect('localhost',"root","shop2020","dtr" )
233
                        cursor = dtrdb.cursor()
234
                        cursor.execute(updateGcmUserSql)
235
                        dtrdb.commit()
236
                        session.commit()
237
                        dtrdb.close()
238
                    except:
239
                        dtrdb.rollback()
240
                        dtrdb.close()
241
 
242
 
15691 manish.sha 243
 
244
def chunks(l, n):
245
    """Yield successive n-sized chunks from l."""
246
    for i in xrange(0, len(l), n):
247
        yield l[i:i+n]
248
 
249
def main():
17228 manish.sha 250
    global userGcmRegIdMap
251
    global campaignsMap
15691 manish.sha 252
    parser = optparse.OptionParser()
253
    parser.add_option("-C", "--chunksize", dest="chunksize",
254
                      default="100",
255
                      type="int", help="The requsets a single thread handles",
256
                      metavar="CHUNKSIZE")
257
    (options, args) = parser.parse_args()
258
 
17228 manish.sha 259
 
260
    notificationListReq = urllib2.Request(PENDING_PUSH_NOTIFICATION_URL)
261
    notificationListResponse = urllib2.urlopen(notificationListReq)
262
    notificationListJson = json.loads(notificationListResponse.read())
263
 
264
    usersList =[]
265
    campaignIdList = []
266
 
267
    for notificationRec in notificationListJson:
268
        if notificationRec.get('user_id') not in usersList:
269
            usersList.append(notificationRec.get('user_id'))
270
        if notificationRec.get('notification_campaign_id') not in campaignIdList:
271
            campaignIdList.append(notificationRec.get('notification_campaign_id'))
272
 
273
    usersList.append(0)
274
    campaignIdList.append(0)
17235 manish.sha 275
    logging.debug('Starting Push Notification Job....'+str(datetime.datetime.now()))
15691 manish.sha 276
 
17229 manish.sha 277
    if len(usersList) >1 and len(campaignIdList)>1:
278
        cursor.execute(GCM_REG_ID_SQL%(str(tuple(usersList))))
279
        result_data = cursor.fetchall()
17228 manish.sha 280
 
17229 manish.sha 281
        for dataRec in result_data:
19065 manish.sha 282
            if userGcmRegIdMap.has_key(dataRec[0]):
283
                gcmRegIdMap = userGcmRegIdMap.get(dataRec[0])
284
                gcmRegIdMap[dataRec[2]]= dataRec[1]
285
                userGcmRegIdMap[dataRec[0]] = gcmRegIdMap
286
            else:
287
                gcmRegIdMap = {}
288
                gcmRegIdMap[dataRec[2]]= dataRec[1]
289
                userGcmRegIdMap[dataRec[0]] = gcmRegIdMap
15691 manish.sha 290
 
17229 manish.sha 291
        cursor.execute(CAMPAIGNS_SQL%(str(tuple(campaignIdList))))
292
        campaign_data = cursor.fetchall()
293
 
294
        for campaignRec in campaign_data:
295
            campaignsMap[campaignRec[0]] = campaignRec    
296
 
297
        count = 1
298
        if result_data:
299
            campaign_receivers_list = list(chunks(notificationListJson, options.chunksize))
300
            print len(campaign_receivers_list)
301
            for sublist in campaign_receivers_list:
302
                thread = NotificationThread(count, "Thread-"+str(count), sublist)
303
                thread.start()
304
                count = count +1
17235 manish.sha 305
 
306
    logging.debug('Stopping Push Notification Job....'+str(datetime.datetime.now()))
17229 manish.sha 307
 
15691 manish.sha 308
    db.close()
309
 
310
if __name__=='__main__':
311
    main()
312