Subversion Repositories SmartDukaan

Rev

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

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