| 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"
|
|
|
45 |
GCM_REG_ID_SQL2 = "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 null order by id desc) as x group by x.user_id, x.gcm_regid"
|
| 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')))
|
| 19095 |
manish.sha |
71 |
campaign = notificationCampaignsMap.get(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]))
|
| 19125 |
manish.sha |
178 |
campaignUsersMap[str(campaign['_id'])]=userids
|
|
|
179 |
notificationCampaignsMap[str(campaign['_id'])] = campaign
|
| 19095 |
manish.sha |
180 |
|
|
|
181 |
def insertPushNotificationEntriesToSent():
|
|
|
182 |
global userGcmRegIdMap
|
|
|
183 |
for userList in campaignUsersMap.values():
|
| 19218 |
manish.sha |
184 |
logging.debug("GCM_REG_SQL_1:- "+GCM_REG_ID_SQL1%(",".join(map(str,userList))))
|
|
|
185 |
cursor.execute(GCM_REG_ID_SQL1%(",".join(map(str,userList))))
|
| 19095 |
manish.sha |
186 |
result_data = cursor.fetchall()
|
|
|
187 |
|
| 19104 |
manish.sha |
188 |
if result_data and len(result_data)>0:
|
| 19122 |
manish.sha |
189 |
user_list = []
|
|
|
190 |
for userId in userList:
|
|
|
191 |
user_list.append(userId)
|
|
|
192 |
|
| 19104 |
manish.sha |
193 |
for dataRec in result_data:
|
| 19217 |
manish.sha |
194 |
'''
|
| 19124 |
manish.sha |
195 |
if str(dataRec[0]) in user_list:
|
| 19122 |
manish.sha |
196 |
user_list.remove(str(dataRec[0]))
|
| 19217 |
manish.sha |
197 |
'''
|
| 19104 |
manish.sha |
198 |
if userGcmRegIdMap.has_key(dataRec[0]):
|
|
|
199 |
detailMap = {}
|
|
|
200 |
gcmRegIdMap = userGcmRegIdMap.get(dataRec[0])
|
|
|
201 |
detailMap['gcm_regid'] = dataRec[1]
|
|
|
202 |
if dataRec[3] is not None:
|
|
|
203 |
detailMap['android_id'] = dataRec[3]
|
|
|
204 |
gcmRegIdMap[dataRec[2]]= detailMap
|
|
|
205 |
userGcmRegIdMap[dataRec[0]] = gcmRegIdMap
|
|
|
206 |
else:
|
|
|
207 |
gcmRegIdMap = {}
|
|
|
208 |
detailMap = {}
|
|
|
209 |
detailMap['gcm_regid'] = dataRec[1]
|
|
|
210 |
if dataRec[3] is not None:
|
|
|
211 |
detailMap['android_id'] = dataRec[3]
|
|
|
212 |
gcmRegIdMap[dataRec[2]]= detailMap
|
|
|
213 |
userGcmRegIdMap[dataRec[0]] = gcmRegIdMap
|
| 19122 |
manish.sha |
214 |
|
| 19125 |
manish.sha |
215 |
logging.debug("Old Users.."+str(user_list))
|
| 19218 |
manish.sha |
216 |
logging.debug("GCM_REG_SQL_2:- "+GCM_REG_ID_SQL2%(",".join(map(str,user_list))))
|
|
|
217 |
cursor.execute(GCM_REG_ID_SQL2%(",".join(map(str,user_list))))
|
| 19104 |
manish.sha |
218 |
result_data = cursor.fetchall()
|
|
|
219 |
for dataRec in result_data:
|
|
|
220 |
if userGcmRegIdMap.has_key(dataRec[0]):
|
|
|
221 |
detailMap = {}
|
|
|
222 |
gcmRegIdMap = userGcmRegIdMap.get(dataRec[0])
|
|
|
223 |
detailMap['gcm_regid'] = dataRec[1]
|
|
|
224 |
if dataRec[3] is not None:
|
|
|
225 |
detailMap['android_id'] = dataRec[3]
|
|
|
226 |
gcmRegIdMap[dataRec[2]]= detailMap
|
|
|
227 |
userGcmRegIdMap[dataRec[0]] = gcmRegIdMap
|
|
|
228 |
else:
|
|
|
229 |
gcmRegIdMap = {}
|
|
|
230 |
detailMap = {}
|
|
|
231 |
detailMap['gcm_regid'] = dataRec[1]
|
|
|
232 |
if dataRec[3] is not None:
|
|
|
233 |
detailMap['android_id'] = dataRec[3]
|
|
|
234 |
gcmRegIdMap[dataRec[2]]= detailMap
|
|
|
235 |
userGcmRegIdMap[dataRec[0]] = gcmRegIdMap
|
|
|
236 |
else:
|
| 19218 |
manish.sha |
237 |
logging.debug("GCM_REG_SQL_2:- "+GCM_REG_ID_SQL2%(",".join(map(str,userList))))
|
|
|
238 |
cursor.execute(GCM_REG_ID_SQL2%(",".join(map(str,userList))))
|
| 19104 |
manish.sha |
239 |
result_data = cursor.fetchall()
|
|
|
240 |
for dataRec in result_data:
|
|
|
241 |
if userGcmRegIdMap.has_key(dataRec[0]):
|
|
|
242 |
detailMap = {}
|
|
|
243 |
gcmRegIdMap = userGcmRegIdMap.get(dataRec[0])
|
|
|
244 |
detailMap['gcm_regid'] = dataRec[1]
|
|
|
245 |
if dataRec[3] is not None:
|
|
|
246 |
detailMap['android_id'] = dataRec[3]
|
|
|
247 |
gcmRegIdMap[dataRec[2]]= detailMap
|
|
|
248 |
userGcmRegIdMap[dataRec[0]] = gcmRegIdMap
|
|
|
249 |
else:
|
|
|
250 |
gcmRegIdMap = {}
|
|
|
251 |
detailMap = {}
|
|
|
252 |
detailMap['gcm_regid'] = dataRec[1]
|
|
|
253 |
if dataRec[3] is not None:
|
|
|
254 |
detailMap['android_id'] = dataRec[3]
|
|
|
255 |
gcmRegIdMap[dataRec[2]]= detailMap
|
| 19117 |
manish.sha |
256 |
userGcmRegIdMap[dataRec[0]] = gcmRegIdMap
|
|
|
257 |
|
|
|
258 |
logging.debug("CampaignUsersMap"+str(campaignUsersMap))
|
| 19095 |
manish.sha |
259 |
|
|
|
260 |
for campaignId, userList in campaignUsersMap.items():
|
|
|
261 |
for userId in userList:
|
| 19122 |
manish.sha |
262 |
gcmRegIdMap = userGcmRegIdMap.get(long(userId))
|
| 19095 |
manish.sha |
263 |
if gcmRegIdMap is None:
|
|
|
264 |
gcmRegIdMap = {}
|
|
|
265 |
for gcm_id, details in gcmRegIdMap.items():
|
|
|
266 |
android_id = None
|
| 19122 |
manish.sha |
267 |
logging.debug("User Id:- "+str(userId)+" ..User Details:- "+str(details))
|
| 19095 |
manish.sha |
268 |
if details.has_key('android_id'):
|
|
|
269 |
android_id = details['android_id']
|
| 19126 |
manish.sha |
270 |
pushNotificationObj = __PushNotification(str(campaignId), long(userId), None, 'pending', \
|
| 19217 |
manish.sha |
271 |
None, None, android_id, "php", None, None, None, None, gcm_id, to_java_date(datetime.now()),0,0)
|
| 19122 |
manish.sha |
272 |
get_mongo_connection(host=mongoHost).User.pushnotifications.insert(pushNotificationObj.__dict__)
|
| 19095 |
manish.sha |
273 |
|
|
|
274 |
def populatePendingNotificationEntriesToBeSent():
|
|
|
275 |
global pendingNotificationEntryMap
|
| 19122 |
manish.sha |
276 |
pendingNotificationEntries = list(get_mongo_connection(host=mongoHost).User.pushnotifications.find({'type':'pending'}))
|
| 19095 |
manish.sha |
277 |
for entry in pendingNotificationEntries:
|
|
|
278 |
if pendingNotificationEntryMap.has_key(entry['notification_campaign_id']):
|
|
|
279 |
entries = pendingNotificationEntryMap.get(entry['notification_campaign_id'])
|
|
|
280 |
entries.append(entry)
|
|
|
281 |
pendingNotificationEntryMap[entry['notification_campaign_id']] = entries
|
|
|
282 |
else:
|
|
|
283 |
entries = []
|
|
|
284 |
entries.append(entry)
|
|
|
285 |
pendingNotificationEntryMap[entry['notification_campaign_id']] = entries
|
|
|
286 |
|
|
|
287 |
def initiateNotificationThreadProcess(chunkSize):
|
|
|
288 |
count = 1
|
| 19104 |
manish.sha |
289 |
logging.debug('Starting Push Notification Job....'+str(datetime.now()))
|
| 19095 |
manish.sha |
290 |
for entries in pendingNotificationEntryMap.values():
|
|
|
291 |
campaign_receivers_list = list(chunks(entries, chunkSize))
|
|
|
292 |
print len(campaign_receivers_list)
|
|
|
293 |
for sublist in campaign_receivers_list:
|
|
|
294 |
thread = NotificationThread(count, "Thread-"+str(count), sublist)
|
|
|
295 |
thread.start()
|
|
|
296 |
count = count +1
|
| 19104 |
manish.sha |
297 |
logging.debug('Stopping Push Notification Job....'+str(datetime.now()))
|
| 19095 |
manish.sha |
298 |
|
| 19104 |
manish.sha |
299 |
def markNotificationCampaignsProcessed():
|
|
|
300 |
for campaign in notificationCampaignsMap.values():
|
| 19125 |
manish.sha |
301 |
logging.debug('Notification Campaign....'+str(campaign.get('_id'))+"...Marked Processed. "+str(datetime.now()))
|
| 19104 |
manish.sha |
302 |
get_mongo_connection(host=mongoHost).User.notificationcampaigns.update({'_id':campaign.get('_id')},{"$set":{'notification_processed':1}})
|
|
|
303 |
|
| 19095 |
manish.sha |
304 |
def main():
|
|
|
305 |
global mongoHost
|
|
|
306 |
parser = optparse.OptionParser()
|
|
|
307 |
parser.add_option("-C", "--chunksize", dest="chunksize",
|
|
|
308 |
default="100",
|
|
|
309 |
type="int", help="The requsets a single thread handles",
|
|
|
310 |
metavar="CHUNKSIZE")
|
|
|
311 |
parser.add_option("-M", "--mongo_host", dest="mongo_host",
|
|
|
312 |
default="localhost",
|
|
|
313 |
type="str", help="The requsets a single thread handles",
|
|
|
314 |
metavar="MONGOHOST")
|
|
|
315 |
(options, args) = parser.parse_args()
|
|
|
316 |
mongoHost = options.mongo_host
|
|
|
317 |
pendingCampaigns = getPendingCampaigns()
|
|
|
318 |
populateCampaignsMap(pendingCampaigns)
|
|
|
319 |
insertPushNotificationEntriesToSent()
|
|
|
320 |
populatePendingNotificationEntriesToBeSent()
|
|
|
321 |
initiateNotificationThreadProcess(options.chunksize)
|
| 19104 |
manish.sha |
322 |
markNotificationCampaignsProcessed()
|
|
|
323 |
|
|
|
324 |
db.close()
|
| 19095 |
manish.sha |
325 |
|
|
|
326 |
if __name__=='__main__':
|
|
|
327 |
main()
|
|
|
328 |
|