Subversion Repositories SmartDukaan

Rev

Rev 19065 | Go to most recent revision | Show entire file | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

Rev 19065 Rev 19066
Line 23... Line 23...
23
 
23
 
24
GCM_URL = "https://android.googleapis.com/gcm/send"
24
GCM_URL = "https://android.googleapis.com/gcm/send"
25
GOOGLE_API_KEY = "AIzaSyDw1qBnmxtnfR9NqBewryQ-yo3cG2ravGM"
25
GOOGLE_API_KEY = "AIzaSyDw1qBnmxtnfR9NqBewryQ-yo3cG2ravGM"
26
PENDING_PUSH_NOTIFICATION_URL = "http://45.33.50.227:3001/getPendingNotifications"
26
PENDING_PUSH_NOTIFICATION_URL = "http://45.33.50.227:3001/getPendingNotifications"
27
PUSH_NOTIFICATIONS_UPDATE_URL = "http://45.33.50.227:3001/updatePushNotification/?"
27
PUSH_NOTIFICATIONS_UPDATE_URL = "http://45.33.50.227:3001/updatePushNotification/?"
28
PUSH_NOTIFICATIONS_ADD_URL = "http://45.33.50.227:3001/addPushNotification"
-
 
29
headers = {'content-type':'application/json', "authorization":"key=" + GOOGLE_API_KEY}
28
headers = {'content-type':'application/json', "authorization":"key=" + GOOGLE_API_KEY}
30
aff_url_headers = { 
29
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',
30
            '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',      
31
            'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',      
33
            'Accept-Language' : 'en-US,en;q=0.8',                     
32
            'Accept-Language' : 'en-US,en;q=0.8',                     
Line 39... Line 38...
39
cursor = db.cursor()
38
cursor = db.cursor()
40
userGcmRegIdMap = {}
39
userGcmRegIdMap = {}
41
campaignsMap = {}
40
campaignsMap = {}
42
 
41
 
43
ALL_STORES_SQL = "select * from stores"
42
ALL_STORES_SQL = "select * from stores"
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"
43
GCM_REG_ID_SQL = "select x.user_id, x.gcm_regid from (select * from gcm_users where user_id in %s order by id desc) as x group by x.user_id"
45
CAMPAIGNS_SQL = "select * from notification_campaigns where id in %s order by id"
44
CAMPAIGNS_SQL = "select * from notification_campaigns where id in %s order by id"
46
 
45
 
47
 
46
 
48
cursor.execute(ALL_STORES_SQL)
47
cursor.execute(ALL_STORES_SQL)
49
result_stores = cursor.fetchall()
48
result_stores = cursor.fetchall()
Line 67... Line 66...
67
    url = None
66
    url = None
68
    expiresAt = None
67
    expiresAt = None
69
    notificationStatus = None
68
    notificationStatus = None
70
    notificationCreated = None
69
    notificationCreated = None
71
    gcmRegId = None
70
    gcmRegId = None
72
    imeinumber = None
-
 
73
    
71
    
74
    def __init__(self,pushNotificationId, userId, campaignId, campaignName, title, message, type, url, expiresAt, notificationStatus, notificationCreated, gcmRegId, imeinumber):
72
    def __init__(self,pushNotificationId, userId, campaignId, campaignName, title, message, type, url, expiresAt, notificationStatus, notificationCreated, gcmRegId):
75
        self.pushNotificationId = pushNotificationId
73
        self.pushNotificationId = pushNotificationId
76
        self.userId = userId
74
        self.userId = userId
77
        self.campaignId = campaignId
75
        self.campaignId = campaignId
78
        self.campaignName = campaignName
76
        self.campaignName = campaignName
79
        self.title = title
77
        self.title = title
Line 82... Line 80...
82
        self.url = url
80
        self.url = url
83
        self.expiresAt = expiresAt
81
        self.expiresAt = expiresAt
84
        self.notificationStatus = notificationStatus
82
        self.notificationStatus = notificationStatus
85
        self.notificationCreated = notificationCreated
83
        self.notificationCreated = notificationCreated
86
        self.gcmRegId = gcmRegId
84
        self.gcmRegId = gcmRegId
87
        self.imeinumber = imeinumber
-
 
88
        
85
        
89
        
86
        
90
class NotificationThread (threading.Thread):
87
class NotificationThread (threading.Thread):
91
    def __init__(self, threadID, name, recordsList):
88
    def __init__(self, threadID, name, recordsList):
92
        threading.Thread.__init__(self)
89
        threading.Thread.__init__(self)
Line 99... Line 96...
99
        logging.debug('Completed')
96
        logging.debug('Completed')
100
 
97
 
101
def handleCampaignRequest(threadName, recordsList ):
98
def handleCampaignRequest(threadName, recordsList ):
102
    for record in recordsList:
99
    for record in recordsList:
103
        campaignRecord = campaignsMap.get(record.get('notification_campaign_id'))
100
        campaignRecord = campaignsMap.get(record.get('notification_campaign_id'))
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)
101
        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], userGcmRegIdMap.get(record.get('user_id')))
110
            if notificationRecord.type=='url':
102
        if notificationRecord.type=='url':
111
                parsed_uri = urlparse(notificationRecord.url)
103
            parsed_uri = urlparse(notificationRecord.url)
112
                domain = '{uri.netloc}'.format(uri=parsed_uri)
104
            domain = '{uri.netloc}'.format(uri=parsed_uri)
113
                logging.debug('Affiliate Domain:-'+str(domain))
105
            logging.debug('Affiliate Domain:-'+str(domain))
114
                logging.debug('User Id:-'+str(notificationRecord.userId)+' And GCM Reg Id:- '+ str(notificationRecord.gcmRegId))
106
            logging.debug('User Id:-'+str(notificationRecord.userId)+' And GCM Reg Id:- '+ str(notificationRecord.gcmRegId))
115
                store = domainStoresMap.get(domain)
107
            store = domainStoresMap.get(domain)
116
                if store is not None:
108
            if store is not None:
117
                    url_params = { 'url' : notificationRecord.url,  'userId' : notificationRecord.userId, 'storeId' : store[0] }
109
                url_params = { 'url' : notificationRecord.url,  'userId' : notificationRecord.userId, 'storeId' : store[0] }
118
                    encoded_url_params = urllib.urlencode(url_params)
110
                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))
-
 
137
                    else:
-
 
138
                        logging.debug('User Id:-'+str(notificationRecord.userId)+' Notification Url:- '+ str(notificationRecord.url))
-
 
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))
-
 
169
                else:
-
 
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()
-
 
189
            
-
 
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
                
111
                
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()
112
                DTR_API_BASIC_AUTH = base64.encodestring('%s:%s' % ("dtr", "dtr18Feb2015")).replace('\n', '')
207
                
113
                
208
                response = requests.post(GCM_URL, data=post_data_json, headers=headers)
114
                pushpostrequest = urllib2.Request('http://api.profittill.com/pushnotifications/generateAffiliateUrl', encoded_url_params, headers=aff_url_headers)
209
                logging.debug('User Id:- '+str(notificationRecord.userId)+' Imeinumber:- '+str(notificationRecord.imeinumber)+' Response :-'+str(response.text))
115
                pushpostrequest.add_header("Authorization", "Basic %s" % DTR_API_BASIC_AUTH)
210
                result = json.loads(response.text)
116
                json_result =  json.loads(urllib2.urlopen(pushpostrequest).read())
211
    
-
 
212
                if result["success"]:                    
117
                notificationRecord.url = json_result['url']
213
                    update_params = { 'user_id' : notificationRecord.userId,  'notification_campaign_id' : notificationRecord.campaignId, 'type' : 'sent', 'status':1, 'message':'success', 'imei':str(notificationRecord.imeinumber) }
118
                logging.debug('User Id:-'+str(notificationRecord.userId)+' Notification Url:- '+ str(notificationRecord.url))
214
                    encoded_update_params = urllib.urlencode(update_params)
119
            else:
215
                    updateReq = urllib2.Request(PUSH_NOTIFICATIONS_UPDATE_URL+encoded_update_params)
120
                queryString = urlparse(notificationRecord.url.strip()).query
216
                    updateResponse = urllib2.urlopen(updateReq)
121
                parsed_url = parse_qs(queryString)
217
                    response_str = updateResponse.read()
122
                if not parsed_url.has_key('user_id'):
218
                    successMarked = True
123
                    if len(queryString)>0:
-
 
124
                        notificationRecord.url = notificationRecord.url.strip()+'&user_id='+str(notificationRecord.userId)
219
                    logging.debug('User Id:- '+str(notificationRecord.userId)+' Imeinumber:- '+str(notificationRecord.imeinumber)+' Update Response :-'+str(response_str))
125
                        logging.debug('User Id:-'+str(notificationRecord.userId)+' Notification Url:- '+ str(notificationRecord.url))
220
                        
126
                    else:
-
 
127
                        notificationRecord.url = notificationRecord.url.strip()+'?user_id='+str(notificationRecord.userId)
-
 
128
                        logging.debug('User Id:-'+str(notificationRecord.userId)+' Notification Url:- '+ str(notificationRecord.url))
221
                else:
129
                else:
-
 
130
                    logging.debug('User Id:-'+str(notificationRecord.userId)+' Notification Url:- '+ str(notificationRecord.url))
-
 
131
        if notificationRecord.url is None or str(notificationRecord.url)=='':
-
 
132
            notificationRecord.url = 'http://api.profittill.com/deals?user_id='+str(notificationRecord.userId)
-
 
133
        data = {"message":notificationRecord.message,"cid":notificationRecord.campaignId,"title":notificationRecord.title,
-
 
134
                "type":notificationRecord.type,"url":notificationRecord.url.strip(),"vibrate":1,"sound":1,"largeIcon":"large_icon",
-
 
135
                "smallIcon":"small_icon","priority":"high","time_to_live":long(time.mktime(notificationRecord.expiresAt.timetuple()))-long(time.mktime(datetime.datetime.now().timetuple()))}
-
 
136
        
-
 
137
        post_data = {}
-
 
138
        
-
 
139
        post_data['data'] = data
-
 
140
        regIds = []
-
 
141
        regIds.append(notificationRecord.gcmRegId)
-
 
142
        post_data['registration_ids'] = regIds
-
 
143
         
-
 
144
        post_data_json = json.dumps(post_data)
-
 
145
        logging.debug('User Id:- '+str(notificationRecord.userId)+' Post Data Json :- '+str(post_data_json))
-
 
146
        
-
 
147
        response = requests.post(GCM_URL, data=post_data_json, headers=headers)
-
 
148
        logging.debug('User Id:- '+str(notificationRecord.userId)+' Response :-'+str(response.text))
-
 
149
        result = json.loads(response.text)
-
 
150
        
-
 
151
        if result["success"]:
-
 
152
            update_params = { 'user_id' : notificationRecord.userId,  'notification_campaign_id' : notificationRecord.campaignId, 'oldType':'pending', 'type' : 'sent', 'status':1, 'message':'success' }
-
 
153
            encoded_update_params = urllib.urlencode(update_params)
-
 
154
            updateReq = urllib2.Request(PUSH_NOTIFICATIONS_UPDATE_URL+encoded_update_params)
-
 
155
            updateResponse = urllib2.urlopen(updateReq)
-
 
156
            response_str = updateResponse.read()
-
 
157
            logging.debug('User Id:- '+str(notificationRecord.userId)+' Update Response :-'+str(response_str))
-
 
158
        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) }
159
            update_params = { 'user_id' : notificationRecord.userId,  'notification_campaign_id' : notificationRecord.campaignId, 'oldType':'pending', 'type' : 'sent', 'status':0, 'message':result["results"][0]["error"] }
223
                    encoded_update_params = urllib.urlencode(update_params)
160
            encoded_update_params = urllib.urlencode(update_params)
224
                    updateReq = urllib2.Request(PUSH_NOTIFICATIONS_UPDATE_URL+encoded_update_params)
161
            updateReq = urllib2.Request(PUSH_NOTIFICATIONS_UPDATE_URL+encoded_update_params)
225
                    updateResponse = urllib2.urlopen(updateReq)
162
            updateResponse = urllib2.urlopen(updateReq)
226
                    response_str = updateResponse.read()
163
            response_str = updateResponse.read()
227
                    logging.debug('User Id:- '+str(notificationRecord.userId)+' Imeinumber:- '+str(notificationRecord.imeinumber)+' Update Response :-'+str(response_str))
164
            logging.debug('User Id:- '+str(notificationRecord.userId)+' Update Response :-'+str(response_str))
228
                    
165
            
229
                    updateGcmUserSql = "update gcm_users set failurecount=failurecount+1 where gcm_regid='%s'"%(notificationRecord.gcmRegId)
166
            updateGcmUserSql = "update gcm_users set failurecount=failurecount+1 where gcm_regid='%s'"%(notificationRecord.gcmRegId)
230
                    logging.debug('Update GCM User Query :-'+str(updateGcmUserSql))
167
            logging.debug('Update GCM User Query :-'+str(updateGcmUserSql))
231
                    try:
168
            try:
232
                        dtrdb = MySQLdb.connect('localhost',"root","shop2020","dtr" )
169
                dtrdb = MySQLdb.connect('localhost',"root","shop2020","dtr" )
233
                        cursor = dtrdb.cursor()
170
                cursor = dtrdb.cursor()
234
                        cursor.execute(updateGcmUserSql)
171
                cursor.execute(updateGcmUserSql)
235
                        dtrdb.commit()
172
                dtrdb.commit()
236
                        session.commit()
173
                session.commit()
237
                        dtrdb.close()
174
                dtrdb.close()
238
                    except:
175
            except:
239
                        dtrdb.rollback()
176
                dtrdb.rollback()
240
                        dtrdb.close()
177
                dtrdb.close()
241
                    
178
            #time.sleep(2)
242
                
-
 
243
 
179
 
244
def chunks(l, n):
180
def chunks(l, n):
245
    """Yield successive n-sized chunks from l."""
181
    """Yield successive n-sized chunks from l."""
246
    for i in xrange(0, len(l), n):
182
    for i in xrange(0, len(l), n):
247
        yield l[i:i+n]
183
        yield l[i:i+n]
Line 277... Line 213...
277
    if len(usersList) >1 and len(campaignIdList)>1:
213
    if len(usersList) >1 and len(campaignIdList)>1:
278
        cursor.execute(GCM_REG_ID_SQL%(str(tuple(usersList))))
214
        cursor.execute(GCM_REG_ID_SQL%(str(tuple(usersList))))
279
        result_data = cursor.fetchall()
215
        result_data = cursor.fetchall()
280
        
216
        
281
        for dataRec in result_data:
217
        for dataRec in result_data:
282
            if userGcmRegIdMap.has_key(dataRec[0]):
-
 
283
                gcmRegIdMap = userGcmRegIdMap.get(dataRec[0])
-
 
284
                gcmRegIdMap[dataRec[2]]= dataRec[1]
218
            userGcmRegIdMap[dataRec[0]] = dataRec[1]
285
                userGcmRegIdMap[dataRec[0]] = gcmRegIdMap
-
 
286
            else:
-
 
287
                gcmRegIdMap = {}
-
 
288
                gcmRegIdMap[dataRec[2]]= dataRec[1]
-
 
289
                userGcmRegIdMap[dataRec[0]] = gcmRegIdMap
-
 
290
            
219
            
291
        cursor.execute(CAMPAIGNS_SQL%(str(tuple(campaignIdList))))
220
        cursor.execute(CAMPAIGNS_SQL%(str(tuple(campaignIdList))))
292
        campaign_data = cursor.fetchall()
221
        campaign_data = cursor.fetchall()
293
        
222
        
294
        for campaignRec in campaign_data:
223
        for campaignRec in campaign_data: