Rev 19753 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed
import MySQLdbfrom elixir import *from sqlalchemy.orm.exc import NoResultFound, MultipleResultsFoundfrom sqlalchemy.sql import funcfrom sqlalchemy.sql.expression import and_, or_, desc, not_, distinct, cast, \betweenimport optparseimport urllib2import base64import urllibimport loggingfrom dtr.utils.utils import get_mongo_connection, to_java_date, num_encodefrom datetime import datetime, timedeltafrom dtr.storage import DataServicefrom dtr.storage.DataService import Usersimport tracebackimport timePROMOTIONAL_SMS_SEND_URL = "http://103.15.179.45:8085/MessagingGateway/SendTransSMS?"TRANSACTIONAL_SMS_SEND_URL = "http://103.15.179.45:8085/SMSGateway/sendingSMS?"DataService.initialize(db_hostname="192.168.158.89")logging.basicConfig(level=logging.DEBUG)mongoHost = 'localhost'def main():global mongoHostparser = optparse.OptionParser()parser.add_option("-M", "--mongo_host", dest="mongo_host",default="localhost",type="str", help="The requsets a single thread handles",metavar="MONGOHOST")(options, args) = parser.parse_args()mongoHost = options.mongo_hostlogging.debug('Starting SMS Blaster Process.....'+str(datetime.now()))timeCondition = datetime.now()-timedelta(hours=2)expireTimeCondition = datetime.now()+timedelta(hours=2)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)}}))for notificationCampaign in eligibleSmsNotficationCampaigns:logging.debug('Notification_Campign_Id:- '+str(notificationCampaign.get('_id')))get_mongo_connection(host=mongoHost).User.notificationcampaigns.update({'_id':notificationCampaign.get('_id')},{"$set":{'smsprocessed':1}})pushnotifications = list(get_mongo_connection(host=mongoHost).User.pushnotifications.find({'notification_campaign_id':notificationCampaign.get('_id')}))pushnotificationUsersMap = {}notificationSuccessUsers = []smsToBeSentUsersMap = {}for entry in pushnotifications:if str(entry.get('type'))!='sent' and entry.get('user_id') not in notificationSuccessUsers:notificationSuccessUsers.append(entry.get('user_id'))if pushnotificationUsersMap.has_key(entry.get('user_id')):entries = pushnotificationUsersMap.get(entry.get('user_id'))entries.append(entry)pushnotificationUsersMap[entry.get('user_id')] = entrieselse:entries = []entries.append(entry)pushnotificationUsersMap[entry.get('user_id')] = entriesfor userId, entries in pushnotificationUsersMap.items():if userId in notificationSuccessUsers:continueentry = entries[0]smsToBeSentUsersMap[userId] = entryif len(smsToBeSentUsersMap.keys())==0:continueallUsers = Users.query.filter(Users.id.in_(tuple(smsToBeSentUsersMap.keys()))).all()sentSmsUsers = []proSmsResponseIdMap = {}tranSmsResponseIdMap = {}for user in allUsers:if user.mobile_number is not None and len(user.mobile_number)==10 and user.mobile_number not in sentSmsUsers:smsUrl='http://pm1.in/A/' + num_encode(notificationCampaign.get('_id')) + '/' + num_encode(user.id)smstext = str(notificationCampaign.get('messagetext')) + ' ' + smsUrl#url_params = { 'Mobile' : '91'+user.mobile_number, 'Username' : 'srlsaholicP', 'Password' : 'srp8oct' , 'MessageType' : 'txt', 'SenderID' : '090000', 'Message' : notificationCampaign.messagetext }url_params = ''if "TRAN_SMS" in smstext:#url_params = { 'ani' : '91'+user.mobile_number, 'uname' : 'srlsaholic', 'passwd' : 'sr18mar' , 'cli' : 'PROFTM', 'message' : smstext.replace("TRAN_SMS", "").strip() }url_params = { 'Mobile' : '91'+user.mobile_number, 'Username' : 'srlsaholic', 'Password' : 'sr18mar' , 'MessageType' : 'txt', 'SenderID' : 'PROFTM', 'Message' : smstext }else:url_params = { 'Mobile' : '91'+user.mobile_number, 'Username' : 'srlsaholicP', 'Password' : 'srp8oct' , 'MessageType' : 'txt', 'SenderID' : '090000', 'Message' : smstext }encoded_url_params = urllib.urlencode(url_params)logging.debug('User Id:- '+str(user.id)+' Notification_Campaign_Id:- '+ str(notificationCampaign.get('_id'))+' Url Params:- '+str(encoded_url_params))url = ''if "TRAN_SMS" in smstext:url = TRANSACTIONAL_SMS_SEND_URL + encoded_url_paramselse:url = PROMOTIONAL_SMS_SEND_URL + encoded_url_paramsresponse_str = Nonetry:req = urllib2.Request(url)response = urllib2.urlopen(req)response_str = response.read()except Exception as e:logging.debug('Error while getting response for user id:- '+ str(user.id) +' Mobile Number:- '+str(user.mobile_number))traceback.print_exc()continueentry = smsToBeSentUsersMap.get(user.id)logging.debug('User Id:- '+str(user.id)+' Notification_Campaign_Id:- '+ str(notificationCampaign.get('_id'))+' Sent Response:- '+ str(response_str))get_mongo_connection(host=mongoHost).User.pushnotifications.update({'_id':entry.get('_id')},{"$set":{'sms_type':'smssent','sms_timestamp':to_java_date(datetime.now())}})if "TRAN_SMS" in smstext:if "Message sent successfully to " in response_str:response_str_vals = response_str.split('#')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]}})tranSmsResponseIdMap[user.id] = response_str_vals[0]else:get_mongo_connection(host=mongoHost).User.pushnotifications.update({'_id':entry.get('_id')},{"$set":{'sms_type':'smsrejected','sms_timestamp':to_java_date(datetime.now())}})else:if "mobile no in DND" in response_str:get_mongo_connection(host=mongoHost).User.pushnotifications.update({'_id':entry.get('_id')},{"$set":{'sms_type':'smsrejected','sms_timestamp':to_java_date(datetime.now())}})else:response_vals = response_str.split('\n')logging.debug('Desired Response String:- '+str(response_vals[2]))if len(response_vals)==4 and 'SMS Sent successfully to' in response_vals[2]:if response_vals[2].split('#')[0]!='null':proSmsResponseIdMap[user.id] = response_vals[2].split('#')[0]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]}})sentSmsUsers.append(user.mobile_number)time.sleep(30)for userId, msgId in proSmsResponseIdMap.items():#http://103.15.179.45:8085/MessagingGateway/http/querymsg?user=srlsaholicP&password=srp8oct&apimsgid=PRO02257518del_det_params = {'user' : 'srlsaholicP', 'password' : 'srp8oct' , 'apimsgid' : msgId}encoded_del_det_params = urllib.urlencode(del_det_params)del_det_url = 'http://103.15.179.45:8085/MessagingGateway/http/querymsg?' + encoded_del_det_paramslogging.debug('Delivery Report Url:- '+del_det_url)try:del_req = urllib2.Request(del_det_url)del_response = urllib2.urlopen(del_req)del_response_str = del_response.read()logging.debug('Delivery Report Response:- '+str(del_response_str))if 'STATUS' in del_response_str:status = del_response_str.split(' ')[3]if status=='DELIVRD':status = 'SMS_DELIVRD'elif status=='SENT':status = 'SMS_SENT_OPERATOR'elif status=='REJECTD' or status== 'FAILED':status = 'SMS_FAILED'elif 'EXP_' in status:status = 'SMS_EXPIRED'else:status = 'SMS_'+statusentry = smsToBeSentUsersMap.get(userId)get_mongo_connection(host=mongoHost).User.pushnotifications.update({'_id':entry.get('_id')},{"$set":{'sms_type':status,'sms_timestamp':to_java_date(datetime.now())}})except Exception as e:logging.debug('Error while getting response for message id:- '+ msgId)traceback.print_exc()continuefor userId, msgId in tranSmsResponseIdMap.items():status = ''if msgId == "No_Response":status = 'SMS_FAILED'else:del_det_params = {'uname' : 'srlsaholic', 'passwd' : 'sr18mar' , 'messageid' : msgId}encoded_del_det_params = urllib.urlencode(del_det_params)del_det_url = 'http://103.15.179.45:8085/SMSGateway/getApiReport?' + encoded_del_det_paramslogging.debug('Delivery Report Url:- '+del_det_url)try:del_req = urllib2.Request(del_det_url)del_response = urllib2.urlopen(del_req)del_response_str = del_response.read()logging.debug('Delivery Report Response:- '+str(del_response_str))del_response_vals = del_response_str.split(' ')status = ''if len(del_response_vals) == 8 and del_response_vals[7][:-2] == '000':status = 'SMS_DELIVRD'elif "Submitted to SMSC" in del_response_str:status = 'SMS_INPROCESS'else:status = 'SMS_FAILED'except Exception as e:logging.debug('Error while getting response for message id:- '+ msgId)traceback.print_exc()continueget_mongo_connection(host=mongoHost).User.pushnotifications.update({'_id':entry.get('_id')},{"$set":{'sms_type':status,'sms_timestamp':to_java_date(datetime.now())}})logging.debug('Total Sms Sent:- '+str(len(sentSmsUsers)))logging.debug('SMS Blaster Process Completed.....'+str(datetime.now()))if __name__=='__main__':main()try:session.close()except:print 'Error while closing session'