| 19095 |
manish.sha |
1 |
#!/usr/bin/python
|
|
|
2 |
|
|
|
3 |
import threading
|
|
|
4 |
import time
|
|
|
5 |
import datetime
|
|
|
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
|
|
|
14 |
from urlparse import parse_qs
|
|
|
15 |
import requests
|
|
|
16 |
import json
|
|
|
17 |
import optparse
|
|
|
18 |
import urllib2
|
|
|
19 |
import base64
|
|
|
20 |
import urllib
|
|
|
21 |
import logging
|
|
|
22 |
from dtr.utils.utils import get_mongo_connection, to_java_date
|
|
|
23 |
from datetime import datetime
|
|
|
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"
|
|
|
45 |
GCM_REG_ID_SQL = "select x.user_id, x.gcm_regid, x.id, x.androidid, x.created from (select * from gcm_users where user_id in %s order by id desc) as x group by x.user_id, x.gcm_regid, x.androidid"
|
|
|
46 |
cursor.execute(ALL_STORES_SQL)
|
|
|
47 |
result_stores = cursor.fetchall()
|
|
|
48 |
domainStoresMap = {}
|
|
|
49 |
for rec in result_stores:
|
|
|
50 |
domainStoresMap[rec[2]] = rec
|
|
|
51 |
|
|
|
52 |
logging.basicConfig(level=logging.DEBUG,
|
|
|
53 |
format='[%(levelname)s] (%(threadName)-10s) %(message)s',
|
|
|
54 |
)
|
|
|
55 |
|
|
|
56 |
class NotificationThread (threading.Thread):
|
|
|
57 |
def __init__(self, threadID, name, recordsList):
|
|
|
58 |
threading.Thread.__init__(self)
|
|
|
59 |
self.threadID = threadID
|
|
|
60 |
self.name = name
|
|
|
61 |
self.recordsList = recordsList
|
|
|
62 |
def run(self):
|
|
|
63 |
logging.debug('Starting')
|
|
|
64 |
handleCampaignRequest(self.name, self.recordsList)
|
|
|
65 |
logging.debug('Completed')
|
|
|
66 |
|
|
|
67 |
def handleCampaignRequest(threadName, recordsList ):
|
|
|
68 |
for record in recordsList:
|
|
|
69 |
userGcmRegIdDetails = userGcmRegIdMap.get(record.get('user_id'))
|
|
|
70 |
campaign = notificationCampaignsMap.get(record.get('notification_campaign_id'))
|
|
|
71 |
for gcm_id, detailsMap in userGcmRegIdDetails.items():
|
|
|
72 |
result_url = ""
|
|
|
73 |
if campaign.get('type')=='url':
|
|
|
74 |
parsed_uri = urlparse(campaign.get('url'))
|
|
|
75 |
domain = '{uri.netloc}'.format(uri=parsed_uri)
|
|
|
76 |
logging.debug('Affiliate Domain:-'+str(domain))
|
|
|
77 |
logging.debug('User Id:-'+str(record.get('user_id'))+' And GCM Reg Id:- '+ str(detailsMap.get('gcm_regid')))
|
|
|
78 |
store = domainStoresMap.get(domain)
|
|
|
79 |
if store is not None:
|
|
|
80 |
url_params = { 'url' : campaign.get('url'), 'userId' : record.get('user_id'), 'storeId' : store[0] }
|
|
|
81 |
encoded_url_params = urllib.urlencode(url_params)
|
|
|
82 |
DTR_API_BASIC_AUTH = base64.encodestring('%s:%s' % ("dtr", "dtr18Feb2015")).replace('\n', '')
|
|
|
83 |
|
|
|
84 |
pushpostrequest = urllib2.Request('http://api.profittill.com/pushnotifications/generateAffiliateUrl', encoded_url_params, headers=aff_url_headers)
|
|
|
85 |
pushpostrequest.add_header("Authorization", "Basic %s" % DTR_API_BASIC_AUTH)
|
|
|
86 |
json_result = json.loads(urllib2.urlopen(pushpostrequest).read())
|
|
|
87 |
result_url = json_result['url']
|
|
|
88 |
logging.debug('User Id:-'+str(record.get('user_id'))+' Notification Url:- '+ str(result_url))
|
|
|
89 |
else:
|
|
|
90 |
queryString = urlparse(campaign.get('url').strip()).query
|
|
|
91 |
parsed_url = parse_qs(queryString)
|
|
|
92 |
if not parsed_url.has_key('user_id'):
|
|
|
93 |
if len(queryString)>0:
|
|
|
94 |
result_url = campaign.get('url').strip()+'&user_id='+str(record.get('user_id'))
|
|
|
95 |
logging.debug('User Id:-'+str(record.get('user_id'))+' Notification Url:- '+ str(result_url))
|
|
|
96 |
else:
|
|
|
97 |
result_url = campaign.get('url').strip()+'?user_id='+str(record.get('user_id'))
|
|
|
98 |
logging.debug('User Id:-'+str(record.get('user_id'))+' Notification Url:- '+ str(result_url))
|
|
|
99 |
else:
|
|
|
100 |
logging.debug('User Id:-'+str(record.get('user_id'))+' Notification Url:- '+ str(record.get('user_id')))
|
|
|
101 |
if campaign.get('url') is None or str(campaign.get('url'))=='':
|
|
|
102 |
result_url = 'http://api.profittill.com/deals?user_id='+str(record.get('user_id'))
|
|
|
103 |
data = {"message":campaign.get('message'),"cid":str(campaign.get('_id'))+"_"+str(record.get('_id')),"title":campaign.get('title'),
|
|
|
104 |
"type":campaign.get('type'),"url":result_url.strip(),"vibrate":1,"sound":1,"largeIcon":"large_icon",
|
|
|
105 |
"smallIcon":"small_icon","priority":"high","time_to_live":long(campaign.get('expiresat'))-long(time.mktime(datetime.datetime.now().timetuple()))}
|
|
|
106 |
|
|
|
107 |
post_data = {}
|
|
|
108 |
|
|
|
109 |
post_data['data'] = data
|
|
|
110 |
regIds = []
|
|
|
111 |
regIds.append(detailsMap.get('gcm_regid'))
|
|
|
112 |
post_data['registration_ids'] = regIds
|
|
|
113 |
|
|
|
114 |
post_data_json = json.dumps(post_data)
|
|
|
115 |
logging.debug('User Id:- '+str(record.get('user_id'))+' Post Data Json :- '+str(post_data_json))
|
|
|
116 |
response = requests.post(GCM_URL, data=post_data_json, headers=headers)
|
|
|
117 |
logging.debug('User Id:- '+str(record.get('user_id'))+' GCM_ID:- '+str(gcm_id)+' Response :-'+str(response.text))
|
|
|
118 |
result = json.loads(response.text)
|
|
|
119 |
if result["success"]:
|
|
|
120 |
get_mongo_connection(host=mongoHost).User.pushnotificationsnew.update({'_id':record.get('_id')},{"$set":{'message':'success','type':'sent','sent_timestamp':to_java_date(datetime.now())}})
|
|
|
121 |
logging.debug('User Id:- '+str(record.get('user_id'))+' GCM_ID:- '+str(gcm_id)+' Update Response :- Notification Success True')
|
|
|
122 |
else:
|
|
|
123 |
get_mongo_connection(host=mongoHost).User.pushnotificationsnew.update({'_id':record.get('_id')},{"$set":{'message':result["results"][0]["error"],'type':'failed','sent_timestamp':to_java_date(datetime.now())}})
|
|
|
124 |
logging.debug('User Id:- '+str(record.get('user_id'))+' GCM_ID:- '+str(gcm_id)+' Update Response :- Notification Fail True')
|
|
|
125 |
updateGcmUserSql = "update gcm_users set failurecount=failurecount+1 where gcm_regid='%s'"%(detailsMap.get('gcm_regid'))
|
|
|
126 |
logging.debug('Update GCM User Query :-'+str(updateGcmUserSql))
|
|
|
127 |
try:
|
|
|
128 |
dtrdb = MySQLdb.connect('localhost',"root","shop2020","dtr" )
|
|
|
129 |
cursor = dtrdb.cursor()
|
|
|
130 |
cursor.execute(updateGcmUserSql)
|
|
|
131 |
dtrdb.commit()
|
|
|
132 |
session.commit()
|
|
|
133 |
dtrdb.close()
|
|
|
134 |
except:
|
|
|
135 |
dtrdb.rollback()
|
|
|
136 |
dtrdb.close()
|
|
|
137 |
|
|
|
138 |
def chunks(l, n):
|
|
|
139 |
"""Yield successive n-sized chunks from l."""
|
|
|
140 |
for i in xrange(0, len(l), n):
|
|
|
141 |
yield l[i:i+n]
|
|
|
142 |
|
|
|
143 |
class __PushNotification:
|
|
|
144 |
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):
|
|
|
145 |
self.notification_campaign_id = notification_campaign_id
|
|
|
146 |
self.user_id = user_id
|
|
|
147 |
self.message = message
|
|
|
148 |
self.type = type
|
|
|
149 |
self.sms_type = sms_type
|
|
|
150 |
self.sms_id = sms_id
|
|
|
151 |
self.android_id = android_id
|
|
|
152 |
self.pushed_by = pushed_by
|
|
|
153 |
self.sent_timestamp = sent_timestamp
|
|
|
154 |
self.receive_timestamp = receive_timestamp
|
|
|
155 |
self.open_timestamp = open_timestamp
|
|
|
156 |
self.sms_timestamp = sms_timestamp
|
|
|
157 |
self.gcm_id = gcm_id
|
|
|
158 |
self.created_timestamp = created_timestamp
|
|
|
159 |
self.gcm_expired = gcm_expired
|
|
|
160 |
|
|
|
161 |
def getPendingCampaigns():
|
|
|
162 |
campaigns = list(get_mongo_connection(host=mongoHost).User.notificationcampaigns.find({'notification_processed':0,'expiresat':{'$gte':to_java_date(datetime.now())}}))
|
|
|
163 |
return campaigns
|
|
|
164 |
|
|
|
165 |
def populateCampaignsMap(pendingCampaigns):
|
|
|
166 |
global campaignUsersMap
|
|
|
167 |
global notificationCampaignsMap
|
|
|
168 |
for campaign in pendingCampaigns:
|
|
|
169 |
cursor.execute(campaign['sql'])
|
|
|
170 |
user_records = cursor.fetchall()
|
|
|
171 |
userids = []
|
|
|
172 |
for record in user_records:
|
|
|
173 |
if long(record[0]) not in userids:
|
|
|
174 |
userids.append(long(record[0]))
|
|
|
175 |
campaignUsersMap[campaign['_id']]=userids
|
|
|
176 |
notificationCampaignsMap[campaign['_id']] = campaign
|
|
|
177 |
|
|
|
178 |
def insertPushNotificationEntriesToSent():
|
|
|
179 |
global userGcmRegIdMap
|
|
|
180 |
for userList in campaignUsersMap.values():
|
|
|
181 |
cursor.execute(GCM_REG_ID_SQL%(str(tuple(userList))))
|
|
|
182 |
result_data = cursor.fetchall()
|
|
|
183 |
|
|
|
184 |
for dataRec in result_data:
|
|
|
185 |
if userGcmRegIdMap.has_key(dataRec[0]):
|
|
|
186 |
detailMap = {}
|
|
|
187 |
gcmRegIdMap = userGcmRegIdMap.get(dataRec[0])
|
|
|
188 |
detailMap['gcm_regid'] = dataRec[1]
|
|
|
189 |
if dataRec[3] is not None:
|
|
|
190 |
detailMap['android_id'] = dataRec[3]
|
|
|
191 |
gcmRegIdMap[dataRec[2]]= detailMap
|
|
|
192 |
userGcmRegIdMap[dataRec[0]] = gcmRegIdMap
|
|
|
193 |
else:
|
|
|
194 |
gcmRegIdMap = {}
|
|
|
195 |
detailMap = {}
|
|
|
196 |
detailMap['gcm_regid'] = dataRec[1]
|
|
|
197 |
if dataRec[3] is not None:
|
|
|
198 |
detailMap['android_id'] = dataRec[3]
|
|
|
199 |
gcmRegIdMap[dataRec[2]]= detailMap
|
|
|
200 |
userGcmRegIdMap[dataRec[0]] = gcmRegIdMap
|
|
|
201 |
|
|
|
202 |
|
|
|
203 |
for campaignId, userList in campaignUsersMap.items():
|
|
|
204 |
for userId in userList:
|
|
|
205 |
gcmRegIdMap = userGcmRegIdMap.get(userId)
|
|
|
206 |
if gcmRegIdMap is None:
|
|
|
207 |
gcmRegIdMap = {}
|
|
|
208 |
for gcm_id, details in gcmRegIdMap.items():
|
|
|
209 |
android_id = None
|
|
|
210 |
if details.has_key('android_id'):
|
|
|
211 |
android_id = details['android_id']
|
|
|
212 |
pushNotificationObj = __PushNotification(campaignId, userId, None, 'pending', \
|
|
|
213 |
None, None, android_id, "php", None, None, None, None, gcm_id, to_java_date(datetime.now()),None)
|
|
|
214 |
get_mongo_connection(host=mongoHost).User.pushnotificationsnew.insert(pushNotificationObj.__dict__)
|
|
|
215 |
|
|
|
216 |
def populatePendingNotificationEntriesToBeSent():
|
|
|
217 |
global pendingNotificationEntryMap
|
|
|
218 |
pendingNotificationEntries = list(get_mongo_connection(host=mongoHost).User.pushnotificationsnew.find({'type':'pending'}))
|
|
|
219 |
for entry in pendingNotificationEntries:
|
|
|
220 |
if pendingNotificationEntryMap.has_key(entry['notification_campaign_id']):
|
|
|
221 |
entries = pendingNotificationEntryMap.get(entry['notification_campaign_id'])
|
|
|
222 |
entries.append(entry)
|
|
|
223 |
pendingNotificationEntryMap[entry['notification_campaign_id']] = entries
|
|
|
224 |
else:
|
|
|
225 |
entries = []
|
|
|
226 |
entries.append(entry)
|
|
|
227 |
pendingNotificationEntryMap[entry['notification_campaign_id']] = entries
|
|
|
228 |
|
|
|
229 |
def initiateNotificationThreadProcess(chunkSize):
|
|
|
230 |
count = 1
|
|
|
231 |
logging.debug('Starting Push Notification Job....'+str(datetime.datetime.now()))
|
|
|
232 |
for entries in pendingNotificationEntryMap.values():
|
|
|
233 |
campaign_receivers_list = list(chunks(entries, chunkSize))
|
|
|
234 |
print len(campaign_receivers_list)
|
|
|
235 |
for sublist in campaign_receivers_list:
|
|
|
236 |
thread = NotificationThread(count, "Thread-"+str(count), sublist)
|
|
|
237 |
thread.start()
|
|
|
238 |
count = count +1
|
|
|
239 |
logging.debug('Stopping Push Notification Job....'+str(datetime.datetime.now()))
|
|
|
240 |
|
|
|
241 |
|
|
|
242 |
def main():
|
|
|
243 |
global mongoHost
|
|
|
244 |
parser = optparse.OptionParser()
|
|
|
245 |
parser.add_option("-C", "--chunksize", dest="chunksize",
|
|
|
246 |
default="100",
|
|
|
247 |
type="int", help="The requsets a single thread handles",
|
|
|
248 |
metavar="CHUNKSIZE")
|
|
|
249 |
parser.add_option("-M", "--mongo_host", dest="mongo_host",
|
|
|
250 |
default="localhost",
|
|
|
251 |
type="str", help="The requsets a single thread handles",
|
|
|
252 |
metavar="MONGOHOST")
|
|
|
253 |
(options, args) = parser.parse_args()
|
|
|
254 |
mongoHost = options.mongo_host
|
|
|
255 |
pendingCampaigns = getPendingCampaigns()
|
|
|
256 |
populateCampaignsMap(pendingCampaigns)
|
|
|
257 |
insertPushNotificationEntriesToSent()
|
|
|
258 |
populatePendingNotificationEntriesToBeSent()
|
|
|
259 |
initiateNotificationThreadProcess(options.chunksize)
|
|
|
260 |
|
|
|
261 |
if __name__=='__main__':
|
|
|
262 |
main()
|
|
|
263 |
|