| 19108 |
manish.sha |
1 |
import MySQLdb
|
|
|
2 |
from elixir import *
|
|
|
3 |
from sqlalchemy.orm.exc import NoResultFound, MultipleResultsFound
|
|
|
4 |
from sqlalchemy.sql import func
|
|
|
5 |
from sqlalchemy.sql.expression import and_, or_, desc, not_, distinct, cast, \
|
|
|
6 |
between
|
|
|
7 |
import optparse
|
|
|
8 |
import urllib2
|
|
|
9 |
import base64
|
|
|
10 |
import urllib
|
|
|
11 |
import logging
|
|
|
12 |
from dtr.utils.utils import get_mongo_connection, to_java_date, num_encode
|
|
|
13 |
from datetime import datetime, timedelta
|
|
|
14 |
from dtr.storage import DataService
|
|
|
15 |
from dtr.storage.DataService import Users
|
|
|
16 |
import traceback
|
|
|
17 |
import time
|
|
|
18 |
|
|
|
19 |
PROMOTIONAL_SMS_SEND_URL = "http://103.15.179.45:8085/MessagingGateway/SendTransSMS?"
|
|
|
20 |
TRANSACTIONAL_SMS_SEND_URL = "http://103.15.179.45:8085/SMSGateway/sendingSMS?"
|
|
|
21 |
DataService.initialize(db_hostname="192.168.158.89")
|
|
|
22 |
|
|
|
23 |
logging.basicConfig(level=logging.DEBUG)
|
|
|
24 |
mongoHost = 'localhost'
|
|
|
25 |
|
|
|
26 |
def main():
|
|
|
27 |
global mongoHost
|
|
|
28 |
parser = optparse.OptionParser()
|
|
|
29 |
parser.add_option("-M", "--mongo_host", dest="mongo_host",
|
|
|
30 |
default="localhost",
|
|
|
31 |
type="str", help="The requsets a single thread handles",
|
|
|
32 |
metavar="MONGOHOST")
|
|
|
33 |
(options, args) = parser.parse_args()
|
|
|
34 |
mongoHost = options.mongo_host
|
|
|
35 |
logging.debug('Starting SMS Blaster Process.....'+str(datetime.now()))
|
|
|
36 |
timeCondition = datetime.now()-timedelta(hours=2)
|
|
|
37 |
expireTimeCondition = datetime.now()+timedelta(hours=2)
|
|
|
38 |
eligibleSmsNotficationCampaigns = list(get_mongo_connection(host=mongoHost).User.notificationcampaigns.find({'notification_processed':1, 'sendsms':1, 'smsprocessed':0,'created':{'$lte':to_java_date(timeCondition)}, 'expiresat':{'$gte':to_java_date(expireTimeCondition)}}))
|
|
|
39 |
for notificationCampaign in eligibleSmsNotficationCampaigns:
|
| 19131 |
manish.sha |
40 |
logging.debug('Notification_Campign_Id:- '+str(notificationCampaign.get('_id')))
|
| 19108 |
manish.sha |
41 |
get_mongo_connection(host=mongoHost).User.notificationcampaigns.update({'_id':notificationCampaign.get('_id')},{"$set":{'smsprocessed':1}})
|
| 19256 |
manish.sha |
42 |
pushnotifications = list(get_mongo_connection(host=mongoHost).User.pushnotifications.find({'notification_campaign_id':notificationCampaign.get('_id')}))
|
| 19108 |
manish.sha |
43 |
pushnotificationUsersMap = {}
|
|
|
44 |
notificationSuccessUsers = []
|
|
|
45 |
smsToBeSentUsersMap = {}
|
|
|
46 |
for entry in pushnotifications:
|
|
|
47 |
if str(entry.get('type'))!='sent' and entry.get('user_id') not in notificationSuccessUsers:
|
|
|
48 |
notificationSuccessUsers.append(entry.get('user_id'))
|
|
|
49 |
if pushnotificationUsersMap.has_key(entry.get('user_id')):
|
|
|
50 |
entries = pushnotificationUsersMap.get(entry.get('user_id'))
|
|
|
51 |
entries.append(entry)
|
|
|
52 |
pushnotificationUsersMap[entry.get('user_id')] = entries
|
|
|
53 |
else:
|
|
|
54 |
entries = []
|
|
|
55 |
entries.append(entry)
|
|
|
56 |
pushnotificationUsersMap[entry.get('user_id')] = entries
|
|
|
57 |
|
|
|
58 |
for userId, entries in pushnotificationUsersMap.items():
|
|
|
59 |
if userId in notificationSuccessUsers:
|
|
|
60 |
continue
|
|
|
61 |
entry = entries[0]
|
|
|
62 |
smsToBeSentUsersMap[userId] = entry
|
|
|
63 |
|
| 19256 |
manish.sha |
64 |
if len(smsToBeSentUsersMap.keys())==0:
|
|
|
65 |
continue
|
| 19108 |
manish.sha |
66 |
allUsers = Users.query.filter(Users.id.in_(tuple(smsToBeSentUsersMap.keys()))).all()
|
|
|
67 |
|
|
|
68 |
sentSmsUsers = []
|
|
|
69 |
proSmsResponseIdMap = {}
|
|
|
70 |
tranSmsResponseIdMap = {}
|
|
|
71 |
|
|
|
72 |
for user in allUsers:
|
|
|
73 |
if user.mobile_number is not None and len(user.mobile_number)==10 and user.mobile_number not in sentSmsUsers:
|
| 19256 |
manish.sha |
74 |
smsUrl='http://pm1.in/A/' + num_encode(notificationCampaign.get('_id')) + '/' + num_encode(user.id)
|
| 19108 |
manish.sha |
75 |
smstext = str(notificationCampaign.get('messagetext')) + ' ' + smsUrl
|
|
|
76 |
#url_params = { 'Mobile' : '91'+user.mobile_number, 'Username' : 'srlsaholicP', 'Password' : 'srp8oct' , 'MessageType' : 'txt', 'SenderID' : '090000', 'Message' : notificationCampaign.messagetext }
|
|
|
77 |
url_params = ''
|
|
|
78 |
if "TRAN_SMS" in smstext:
|
| 22758 |
amit.gupta |
79 |
#url_params = { 'ani' : '91'+user.mobile_number, 'uname' : 'srlsaholic', 'passwd' : 'sr18mar' , 'cli' : 'PROFTM', 'message' : smstext.replace("TRAN_SMS", "").strip() }
|
| 23356 |
amit.gupta |
80 |
url_params = { 'Mobile' : '91'+user.mobile_number, 'Username' : 'srlsaholic', 'Password' : 'sr18mar' , 'MessageType' : 'txt', 'SenderID' : 'SMTDKN', 'Message' : smstext }
|
| 19108 |
manish.sha |
81 |
else:
|
|
|
82 |
url_params = { 'Mobile' : '91'+user.mobile_number, 'Username' : 'srlsaholicP', 'Password' : 'srp8oct' , 'MessageType' : 'txt', 'SenderID' : '090000', 'Message' : smstext }
|
|
|
83 |
encoded_url_params = urllib.urlencode(url_params)
|
|
|
84 |
logging.debug('User Id:- '+str(user.id)+' Notification_Campaign_Id:- '+ str(notificationCampaign.get('_id'))+' Url Params:- '+str(encoded_url_params))
|
|
|
85 |
url = ''
|
|
|
86 |
if "TRAN_SMS" in smstext:
|
|
|
87 |
url = TRANSACTIONAL_SMS_SEND_URL + encoded_url_params
|
|
|
88 |
else:
|
|
|
89 |
url = PROMOTIONAL_SMS_SEND_URL + encoded_url_params
|
|
|
90 |
response_str = None
|
|
|
91 |
try:
|
|
|
92 |
req = urllib2.Request(url)
|
|
|
93 |
response = urllib2.urlopen(req)
|
|
|
94 |
response_str = response.read()
|
|
|
95 |
except Exception as e:
|
|
|
96 |
logging.debug('Error while getting response for user id:- '+ str(user.id) +' Mobile Number:- '+str(user.mobile_number))
|
|
|
97 |
traceback.print_exc()
|
|
|
98 |
continue
|
|
|
99 |
|
|
|
100 |
entry = smsToBeSentUsersMap.get(user.id)
|
|
|
101 |
logging.debug('User Id:- '+str(user.id)+' Notification_Campaign_Id:- '+ str(notificationCampaign.get('_id'))+' Sent Response:- '+ str(response_str))
|
| 19258 |
manish.sha |
102 |
get_mongo_connection(host=mongoHost).User.pushnotifications.update({'_id':entry.get('_id')},{"$set":{'sms_type':'smssent','sms_timestamp':to_java_date(datetime.now())}})
|
| 19108 |
manish.sha |
103 |
if "TRAN_SMS" in smstext:
|
|
|
104 |
if "Message sent successfully to " in response_str:
|
|
|
105 |
response_str_vals = response_str.split('#')
|
| 19258 |
manish.sha |
106 |
get_mongo_connection(host=mongoHost).User.pushnotifications.update({'_id':entry.get('_id')},{"$set":{'sms_type':'smsprocessed','sms_timestamp':to_java_date(datetime.now()),'sms_id':response_str_vals[0]}})
|
| 19108 |
manish.sha |
107 |
tranSmsResponseIdMap[user.id] = response_str_vals[0]
|
|
|
108 |
else:
|
| 19258 |
manish.sha |
109 |
get_mongo_connection(host=mongoHost).User.pushnotifications.update({'_id':entry.get('_id')},{"$set":{'sms_type':'smsrejected','sms_timestamp':to_java_date(datetime.now())}})
|
| 19108 |
manish.sha |
110 |
else:
|
|
|
111 |
if "mobile no in DND" in response_str:
|
| 19258 |
manish.sha |
112 |
get_mongo_connection(host=mongoHost).User.pushnotifications.update({'_id':entry.get('_id')},{"$set":{'sms_type':'smsrejected','sms_timestamp':to_java_date(datetime.now())}})
|
| 19108 |
manish.sha |
113 |
else:
|
|
|
114 |
response_vals = response_str.split('\n')
|
|
|
115 |
logging.debug('Desired Response String:- '+str(response_vals[2]))
|
|
|
116 |
if len(response_vals)==4 and 'SMS Sent successfully to' in response_vals[2]:
|
|
|
117 |
if response_vals[2].split('#')[0]!='null':
|
|
|
118 |
proSmsResponseIdMap[user.id] = response_vals[2].split('#')[0]
|
| 19258 |
manish.sha |
119 |
get_mongo_connection(host=mongoHost).User.pushnotifications.update({'_id':entry.get('_id')},{"$set":{'sms_type':'smsprocessed','sms_timestamp':to_java_date(datetime.now()),'sms_id':response_vals[2].split('#')[0]}})
|
| 19108 |
manish.sha |
120 |
|
|
|
121 |
sentSmsUsers.append(user.mobile_number)
|
|
|
122 |
|
|
|
123 |
time.sleep(30)
|
|
|
124 |
|
|
|
125 |
for userId, msgId in proSmsResponseIdMap.items():
|
|
|
126 |
#http://103.15.179.45:8085/MessagingGateway/http/querymsg?user=srlsaholicP&password=srp8oct&apimsgid=PRO02257518
|
|
|
127 |
del_det_params = {'user' : 'srlsaholicP', 'password' : 'srp8oct' , 'apimsgid' : msgId}
|
|
|
128 |
encoded_del_det_params = urllib.urlencode(del_det_params)
|
|
|
129 |
del_det_url = 'http://103.15.179.45:8085/MessagingGateway/http/querymsg?' + encoded_del_det_params
|
|
|
130 |
logging.debug('Delivery Report Url:- '+del_det_url)
|
|
|
131 |
try:
|
|
|
132 |
del_req = urllib2.Request(del_det_url)
|
|
|
133 |
del_response = urllib2.urlopen(del_req)
|
|
|
134 |
del_response_str = del_response.read()
|
|
|
135 |
logging.debug('Delivery Report Response:- '+str(del_response_str))
|
|
|
136 |
if 'STATUS' in del_response_str:
|
|
|
137 |
status = del_response_str.split(' ')[3]
|
|
|
138 |
if status=='DELIVRD':
|
|
|
139 |
status = 'SMS_DELIVRD'
|
|
|
140 |
elif status=='SENT':
|
|
|
141 |
status = 'SMS_SENT_OPERATOR'
|
|
|
142 |
elif status=='REJECTD' or status== 'FAILED':
|
|
|
143 |
status = 'SMS_FAILED'
|
|
|
144 |
elif 'EXP_' in status:
|
|
|
145 |
status = 'SMS_EXPIRED'
|
|
|
146 |
else:
|
|
|
147 |
status = 'SMS_'+status
|
|
|
148 |
entry = smsToBeSentUsersMap.get(userId)
|
| 19258 |
manish.sha |
149 |
get_mongo_connection(host=mongoHost).User.pushnotifications.update({'_id':entry.get('_id')},{"$set":{'sms_type':status,'sms_timestamp':to_java_date(datetime.now())}})
|
| 19108 |
manish.sha |
150 |
except Exception as e:
|
|
|
151 |
logging.debug('Error while getting response for message id:- '+ msgId)
|
|
|
152 |
traceback.print_exc()
|
|
|
153 |
continue
|
|
|
154 |
|
|
|
155 |
|
|
|
156 |
for userId, msgId in tranSmsResponseIdMap.items():
|
|
|
157 |
status = ''
|
|
|
158 |
if msgId == "No_Response":
|
|
|
159 |
status = 'SMS_FAILED'
|
|
|
160 |
else:
|
|
|
161 |
del_det_params = {'uname' : 'srlsaholic', 'passwd' : 'sr18mar' , 'messageid' : msgId}
|
|
|
162 |
encoded_del_det_params = urllib.urlencode(del_det_params)
|
|
|
163 |
del_det_url = 'http://103.15.179.45:8085/SMSGateway/getApiReport?' + encoded_del_det_params
|
|
|
164 |
logging.debug('Delivery Report Url:- '+del_det_url)
|
|
|
165 |
try:
|
|
|
166 |
del_req = urllib2.Request(del_det_url)
|
|
|
167 |
del_response = urllib2.urlopen(del_req)
|
|
|
168 |
del_response_str = del_response.read()
|
|
|
169 |
logging.debug('Delivery Report Response:- '+str(del_response_str))
|
|
|
170 |
|
|
|
171 |
del_response_vals = del_response_str.split(' ')
|
|
|
172 |
|
|
|
173 |
status = ''
|
| 19753 |
manas |
174 |
if len(del_response_vals) == 8 and del_response_vals[7][:-2] == '000':
|
| 19108 |
manish.sha |
175 |
status = 'SMS_DELIVRD'
|
|
|
176 |
elif "Submitted to SMSC" in del_response_str:
|
|
|
177 |
status = 'SMS_INPROCESS'
|
|
|
178 |
else:
|
|
|
179 |
status = 'SMS_FAILED'
|
|
|
180 |
|
|
|
181 |
except Exception as e:
|
|
|
182 |
logging.debug('Error while getting response for message id:- '+ msgId)
|
|
|
183 |
traceback.print_exc()
|
|
|
184 |
continue
|
|
|
185 |
|
| 19258 |
manish.sha |
186 |
get_mongo_connection(host=mongoHost).User.pushnotifications.update({'_id':entry.get('_id')},{"$set":{'sms_type':status,'sms_timestamp':to_java_date(datetime.now())}})
|
| 19108 |
manish.sha |
187 |
|
|
|
188 |
logging.debug('Total Sms Sent:- '+str(len(sentSmsUsers)))
|
|
|
189 |
logging.debug('SMS Blaster Process Completed.....'+str(datetime.now()))
|
|
|
190 |
|
|
|
191 |
|
|
|
192 |
if __name__=='__main__':
|
|
|
193 |
main()
|
|
|
194 |
try:
|
|
|
195 |
session.close()
|
|
|
196 |
except:
|
|
|
197 |
print 'Error while closing session'
|