| 15691 |
manish.sha |
1 |
#!/usr/bin/python
|
|
|
2 |
|
|
|
3 |
import threading
|
|
|
4 |
import time
|
|
|
5 |
|
|
|
6 |
import MySQLdb
|
|
|
7 |
from dtr.storage import DataService
|
|
|
8 |
from dtr.storage.DataService import Pushnotifications
|
|
|
9 |
from elixir import *
|
|
|
10 |
from sqlalchemy.orm.exc import NoResultFound, MultipleResultsFound
|
|
|
11 |
from sqlalchemy.sql import func
|
|
|
12 |
from sqlalchemy.sql.expression import and_, or_, desc, not_, distinct, cast, \
|
|
|
13 |
between
|
|
|
14 |
from urlparse import urlparse
|
|
|
15 |
import requests
|
|
|
16 |
import json
|
|
|
17 |
import optparse
|
|
|
18 |
import urllib2
|
|
|
19 |
import base64
|
|
|
20 |
import urllib
|
|
|
21 |
|
|
|
22 |
GCM_URL = "https://android.googleapis.com/gcm/send"
|
|
|
23 |
GOOGLE_API_KEY = "AIzaSyDw1qBnmxtnfR9NqBewryQ-yo3cG2ravGM"
|
|
|
24 |
headers = {'content-type':'application/json', "authorization":"key=" + GOOGLE_API_KEY}
|
|
|
25 |
aff_url_headers = {
|
|
|
26 |
'User-agent':'Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36',
|
|
|
27 |
'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
|
|
|
28 |
'Accept-Language' : 'en-US,en;q=0.8',
|
|
|
29 |
'Accept-Charset' : 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
|
|
|
30 |
'Connection':'keep-alive'
|
|
|
31 |
}
|
|
|
32 |
|
|
|
33 |
db = MySQLdb.connect('localhost',"root","shop2020","dtr" )
|
|
|
34 |
cursor = db.cursor()
|
|
|
35 |
|
| 15727 |
manish.sha |
36 |
PUSH_NOTIFICATIONS_SQL = "select p.id, p.user_id, n.*, g.gcm_regid from pushnotifications p join notification_campaigns n on p.notification_campaign_id = n.id left outer join (select * from (select * from gcm_users order by id desc) as X group by user_id) as g on p.user_id = g.user_id where p.type ='pending'"
|
| 15691 |
manish.sha |
37 |
ALL_STORES_SQL = "select * from stores"
|
|
|
38 |
|
|
|
39 |
cursor.execute(ALL_STORES_SQL)
|
|
|
40 |
result_stores = cursor.fetchall()
|
|
|
41 |
domainStoresMap = {}
|
|
|
42 |
for rec in result_stores:
|
|
|
43 |
domainStoresMap[rec[2]] = rec
|
|
|
44 |
|
|
|
45 |
|
|
|
46 |
class NotificationRecord():
|
|
|
47 |
pushNotificationId = None
|
|
|
48 |
userId = None
|
|
|
49 |
campaignId = None
|
|
|
50 |
campaignName = None
|
|
|
51 |
title = None
|
|
|
52 |
message= None
|
|
|
53 |
type = None
|
|
|
54 |
url = None
|
|
|
55 |
expiresAt = None
|
|
|
56 |
notificationStatus = None
|
|
|
57 |
notificationCreated = None
|
|
|
58 |
gcmRegId = None
|
|
|
59 |
|
|
|
60 |
def __init__(self,pushNotificationId, userId, campaignId, campaignName, title, message, type, url, expiresAt, notificationStatus, notificationCreated, gcmRegId):
|
|
|
61 |
self.pushNotificationId = pushNotificationId
|
|
|
62 |
self.userId = userId
|
|
|
63 |
self.campaignId = campaignId
|
|
|
64 |
self.campaignName = campaignName
|
|
|
65 |
self.title = title
|
|
|
66 |
self.message= message
|
|
|
67 |
self.type = type
|
|
|
68 |
self.url = url
|
|
|
69 |
self.expiresAt = expiresAt
|
|
|
70 |
self.notificationStatus = notificationStatus
|
|
|
71 |
self.notificationCreated = notificationCreated
|
|
|
72 |
self.gcmRegId = gcmRegId
|
|
|
73 |
|
|
|
74 |
|
|
|
75 |
class NotificationThread (threading.Thread):
|
|
|
76 |
def __init__(self, threadID, name, recordsList):
|
|
|
77 |
threading.Thread.__init__(self)
|
|
|
78 |
self.threadID = threadID
|
|
|
79 |
self.name = name
|
|
|
80 |
self.recordsList = recordsList
|
|
|
81 |
def run(self):
|
|
|
82 |
handleCampaignRequest(self.name, self.recordsList)
|
|
|
83 |
|
|
|
84 |
def handleCampaignRequest(threadName, recordsList ):
|
|
|
85 |
for record in recordsList:
|
|
|
86 |
notificationRecord = NotificationRecord(record[0], record[1], record[2], record[3], record[4], record[5], record[6], record[7], record[9], record[10], record[11], record[12])
|
|
|
87 |
if notificationRecord.type=='url':
|
|
|
88 |
parsed_uri = urlparse(notificationRecord.url)
|
|
|
89 |
domain = '{uri.netloc}'.format(uri=parsed_uri)
|
|
|
90 |
print domain
|
|
|
91 |
store = domainStoresMap.get(domain)
|
|
|
92 |
if store is not None:
|
|
|
93 |
url_params = { 'url' : notificationRecord.url, 'userId' : notificationRecord.userId, 'storeId' : store[0] }
|
|
|
94 |
encoded_url_params = urllib.urlencode(url_params)
|
|
|
95 |
|
|
|
96 |
DTR_API_BASIC_AUTH = base64.encodestring('%s:%s' % ("dtr", "dtr18Feb2015")).replace('\n', '')
|
|
|
97 |
|
|
|
98 |
pushpostrequest = urllib2.Request('http://api.profittill.com/pushnotifications/generateAffiliateUrl', encoded_url_params, headers=aff_url_headers)
|
|
|
99 |
pushpostrequest.add_header("Authorization", "Basic %s" % DTR_API_BASIC_AUTH)
|
|
|
100 |
json_result = json.loads(urllib2.urlopen(pushpostrequest).read())
|
|
|
101 |
notificationRecord.url = json_result['url']
|
|
|
102 |
|
|
|
103 |
data = {"message":notificationRecord.message,"cid":notificationRecord.campaignId,"title":notificationRecord.title,
|
|
|
104 |
"type":notificationRecord.type,"url":notificationRecord.url,"vibrate":1,"sound":1,"largeIcon":"large_icon",
|
|
|
105 |
"smallIcon":"small_icon"}
|
|
|
106 |
|
|
|
107 |
post_data = {}
|
|
|
108 |
|
|
|
109 |
post_data['data'] = data
|
| 15724 |
manish.sha |
110 |
regIds = []
|
|
|
111 |
regIds.append(notificationRecord.gcmRegId)
|
|
|
112 |
post_data['registration_ids'] = regIds
|
| 15691 |
manish.sha |
113 |
|
|
|
114 |
post_data_json = json.dumps(post_data)
|
|
|
115 |
print post_data_json
|
|
|
116 |
|
|
|
117 |
response = requests.post(GCM_URL, data=post_data_json, headers=headers)
|
|
|
118 |
print response.text
|
| 15725 |
manish.sha |
119 |
result = json.loads(response.text)
|
| 15691 |
manish.sha |
120 |
pushnotification = Pushnotifications.get_by(id=notificationRecord.pushNotificationId)
|
|
|
121 |
|
|
|
122 |
if result["success"]:
|
|
|
123 |
pushnotification.type = "sent"
|
|
|
124 |
pushnotification.status = True
|
|
|
125 |
pushnotification.message = "success"
|
|
|
126 |
session.commit()
|
|
|
127 |
else:
|
|
|
128 |
pushnotification.type = "sent"
|
|
|
129 |
pushnotification.status = False
|
|
|
130 |
pushnotification.message = result["results"][0]["error"]
|
|
|
131 |
|
|
|
132 |
updateGcmUserSql = "update gcm_users set failurecount=failurecount+1 where gcm_regid='%s'"%(notificationRecord.gcmRegId)
|
|
|
133 |
print updateGcmUserSql
|
|
|
134 |
try:
|
| 15726 |
manish.sha |
135 |
dtrdb = MySQLdb.connect('localhost',"root","shop2020","dtr" )
|
|
|
136 |
cursor = dtrdb.cursor()
|
| 15691 |
manish.sha |
137 |
cursor.execute(updateGcmUserSql)
|
| 15726 |
manish.sha |
138 |
dtrdb.commit()
|
| 15691 |
manish.sha |
139 |
session.commit()
|
| 15726 |
manish.sha |
140 |
dtrdb.close()
|
| 15691 |
manish.sha |
141 |
except:
|
| 15726 |
manish.sha |
142 |
dtrdb.rollback()
|
|
|
143 |
dtrdb.close()
|
| 15691 |
manish.sha |
144 |
|
|
|
145 |
def chunks(l, n):
|
|
|
146 |
"""Yield successive n-sized chunks from l."""
|
|
|
147 |
for i in xrange(0, len(l), n):
|
|
|
148 |
yield l[i:i+n]
|
|
|
149 |
|
|
|
150 |
def main():
|
|
|
151 |
parser = optparse.OptionParser()
|
|
|
152 |
parser.add_option("-C", "--chunksize", dest="chunksize",
|
|
|
153 |
default="100",
|
|
|
154 |
type="int", help="The requsets a single thread handles",
|
|
|
155 |
metavar="CHUNKSIZE")
|
|
|
156 |
(options, args) = parser.parse_args()
|
|
|
157 |
|
|
|
158 |
cursor.execute(PUSH_NOTIFICATIONS_SQL)
|
|
|
159 |
result_data = cursor.fetchall()
|
|
|
160 |
|
|
|
161 |
count = 1
|
|
|
162 |
DataService.initialize(db_hostname="localhost")
|
|
|
163 |
if result_data:
|
|
|
164 |
campaign_receivers_list = list(chunks(result_data, options.chunksize))
|
|
|
165 |
print len(campaign_receivers_list)
|
|
|
166 |
for sublist in campaign_receivers_list:
|
|
|
167 |
thread = NotificationThread(count, "Thread-"+str(count), sublist)
|
|
|
168 |
thread.start()
|
|
|
169 |
count = count +1
|
|
|
170 |
|
|
|
171 |
db.close()
|
|
|
172 |
if session.is_active:
|
|
|
173 |
print "session is active. closing it."
|
|
|
174 |
session.close()
|
|
|
175 |
|
|
|
176 |
if __name__=='__main__':
|
|
|
177 |
main()
|
|
|
178 |
|