Subversion Repositories SmartDukaan

Rev

Rev 18961 | Blame | Compare with Previous | Last modification | View Log | RSS feed

import json
from dtr.storage import DataService
from dtr.storage.DataService import notification_campaigns, Users
import MySQLdb
import pymongo
from elixir import *
from sqlalchemy.orm.exc import NoResultFound, MultipleResultsFound
from sqlalchemy.sql import func
from sqlalchemy.sql.expression import and_, or_, desc, not_, distinct, cast, \
    between
from datetime import datetime
from datetime import timedelta
import urllib
import urllib2
import json
import time
import traceback
import logging
from dtr.utils.utils import num_encode

PUSH_NOTIFICATIONS_DETAILS_URL="http://localhost:3001/getPushNotificationDetailsByType/?type=%s&notification_campaign_id=%d&status=%s"
PROMOTIONAL_SMS_SEND_URL = "http://103.15.179.45:8085/MessagingGateway/SendTransSMS?"
TRANSACTIONAL_SMS_SEND_URL = "http://103.15.179.45:8085/MessagingGateway/SendTransSMS?"
#ID is: PRO02135496 Mobile Number is: 918512809859 PRO02135496#SMS Sent successfully to : 918512809859
#http://103.15.179.45:8085/MessagingGateway/http/querymsg?user=srlsaholicP&password=srp8oct&apimsgid=PRO02257518
#MessageID: PRO02135496 STATUS: DELIVRD ErrorCode: 0 DR Time: 2015-10-20 18:05:11 

DataService.initialize(db_hostname="192.168.158.89")

logging.basicConfig(level=logging.DEBUG)

def main():
    logging.debug('Starting SMS Blaster Process.....'+str(datetime.now()))
    timeCondition = datetime.now()-timedelta(hours=2)
    expireTimeCondition = datetime.now()+timedelta(hours=2)
    eligibleSmsNotficationCampaigns = notification_campaigns.query.filter(notification_campaigns.sendsms==True).filter(or_(notification_campaigns.smsprocessed==False, notification_campaigns.smsprocessed==None)).filter(notification_campaigns.created<timeCondition).filter(notification_campaigns.expiresat>expireTimeCondition).all()
    #eligibleSmsNotficationCampaigns = notification_campaigns.query.filter(notification_campaigns.id==5417).all()
    
    for notificationCampaign in eligibleSmsNotficationCampaigns:
        logging.debug('Notification_Campign_Id:- '+str(notificationCampaign.id))
        notificationCampaign.smsprocessed = True
        session.commit()
        sentFailedresponse = urllib2.urlopen(PUSH_NOTIFICATIONS_DETAILS_URL%('sent',notificationCampaign.id,0)).read()
        jsonList = json.loads(sentFailedresponse)
        userList = []
        for obj in jsonList:
            userList.append(long(obj.get('user_id')))
        logging.debug('Failed User List...'+str(len(userList)))
            
        sentSuccessResponse = urllib2.urlopen(PUSH_NOTIFICATIONS_DETAILS_URL%('sent',notificationCampaign.id,1)).read()
        jsonList = json.loads(sentSuccessResponse)
        for obj in jsonList:
            userList.append(long(obj.get('user_id')))
        
        userList = list(set(userList))
          
        receivedSuccessResponse = urllib2.urlopen(PUSH_NOTIFICATIONS_DETAILS_URL%('recieved',notificationCampaign.id,1)).read()
        jsonList = json.loads(receivedSuccessResponse)
        logging.debug('User List Before...'+str(len(userList)))
        for obj in jsonList:
            if obj.get('user_id') in userList:
                userList.remove(long(obj.get('user_id')))
        logging.debug('User List After...'+str(len(userList)))
        
        allUsers = Users.query.filter(Users.id.in_(tuple(userList))).all()
        #print allUsers
        
        sentSmsUsers = []
        proSmsResponseIdMap = {}
        tranSmsResponseIdMap = {}
        payloadList = []
        
        #smstext = str(notificationCampaign.messagetext) + ' http://bit.ly/1LBesWK'
        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.id) + '/' + num_encode(user.id)
                smstext = str(notificationCampaign.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.id)+' Url Params:- '+str(encoded_url_params))
                url = ''
                if "TRAN_SMS" in smstext:
                    url = TRANSACTIONAL_SMS_SEND_URL + encoded_url_params
                else:
                    url = PROMOTIONAL_SMS_SEND_URL + encoded_url_params
                response_str = None
                try:
                    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()
                    continue
                    
                logging.debug('User Id:- '+str(user.id)+' Notification_Campaign_Id:- '+ str(notificationCampaign.id)+' Sent Response:- '+ str(response_str))
                
                
                payload = {}
                payload["user_id"]= user.id
                payload["type"]="smssent"
                payload["notification_campaign_id"]= notificationCampaign.id
                payload["status"]=1
                
                if len(payloadList)==5000:
                    jsonObj = json.dumps([dict(pn) for pn in payloadList])
                    pushpostrequest = urllib2.Request("http://localhost:3001/addPushNotification")
                    pushpostrequest.add_header('Content-Type', 'application/json')
                    response = urllib2.urlopen(pushpostrequest, jsonObj).read()
                    payloadList = []
                
                payloadList.append(payload)
                
                if "TRAN_SMS" in smstext:
                    if "Message sent successfully to " in response_str:
                        response_str_vals = response_str.split('#')
                        payload = {}
                        payload["user_id"]= user.id
                        payload["type"]="smsprocessed"
                        payload["notification_campaign_id"]= notificationCampaign.id
                        payload["status"]=1
                        payload["sms_id"]=response_str_vals[0]
                        payloadList.append(payload)
                        tranSmsResponseIdMap[user.id] = response_str_vals[0]
                    else:
                        payload = {}
                        payload["user_id"]= user.id
                        payload["type"]="smsrejected"
                        payload["notification_campaign_id"]= notificationCampaign.id
                        payload["status"]=1
                        payloadList.append(payload)
                else:
                    if "mobile no in DND" in response_str:
                        payload = {}
                        payload["user_id"]= user.id
                        payload["type"]="smsrejected"
                        payload["notification_campaign_id"]= notificationCampaign.id
                        payload["status"]=1
                        payloadList.append(payload)
                    else:
                        payload = {}
                        payload["user_id"]= user.id
                        payload["type"]="smsprocessed"
                        payload["notification_campaign_id"]= notificationCampaign.id
                        payload["status"]=1
                        
                        
                        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]
                                payload["sms_id"]=response_vals[2].split('#')[0]
                                payloadList.append(payload)
                sentSmsUsers.append(user.mobile_number)

        time.sleep(120)
        
        for userId, msgId in proSmsResponseIdMap.items():
            #http://103.15.179.45:8085/MessagingGateway/http/querymsg?user=srlsaholicP&password=srp8oct&apimsgid=PRO02257518
            del_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_params
            logging.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_'+status
                        
                    payload = {}
                    payload["user_id"]= userId
                    payload["type"]=status
                    payload["notification_campaign_id"]= notificationCampaign.id
                    payload["status"]=1
                    if status == 'SMS_SENT_OPERATOR':
                        payload["sms_id"] = msgId
                    
                    if len(payloadList)==5000:
                        jsonObj = json.dumps([dict(pn) for pn in payloadList])
                        pushpostrequest = urllib2.Request("http://localhost:3001/addPushNotification")
                        pushpostrequest.add_header('Content-Type', 'application/json')
                        response = urllib2.urlopen(pushpostrequest, jsonObj).read()
                        payloadList = []
                    payloadList.append(payload)
                
            except Exception as e:
                logging.debug('Error while getting response for message id:- '+ msgId)
                traceback.print_exc()
                continue
        
        for userId, msgId in tranSmsResponseIdMap.items():
            if msgId == "No_Response":
                status = 'SMS_FAILED'
                payload = {}
                payload["user_id"]= userId
                payload["type"]=status
                payload["notification_campaign_id"]= notificationCampaign.id
                payload["status"]=1
                if len(payloadList)==5000:
                    jsonObj = json.dumps([dict(pn) for pn in payloadList])
                    pushpostrequest = urllib2.Request("http://localhost:3001/addPushNotification")
                    pushpostrequest.add_header('Content-Type', 'application/json')
                    response = urllib2.urlopen(pushpostrequest, jsonObj).read()
                    payloadList = []
                payloadList.append(payload)
            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_params
                logging.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] == '0':
                        status = 'SMS_DELIVRD'
                    elif "Submitted to SMSC" in del_response_str:
                        status = 'SMS_INPROCESS'
                    else:
                        status = 'SMS_FAILED'
                    payload = {}
                    payload["user_id"]= userId
                    payload["type"]=status
                    payload["notification_campaign_id"]= notificationCampaign.id
                    if status == 'SMS_INPROCESS':
                        payload["sms_id"] = msgId
                    payload["status"]=1
                    if len(payloadList)==5000:
                        jsonObj = json.dumps([dict(pn) for pn in payloadList])
                        pushpostrequest = urllib2.Request("http://localhost:3001/addPushNotification")
                        pushpostrequest.add_header('Content-Type', 'application/json')
                        response = urllib2.urlopen(pushpostrequest, jsonObj).read()
                        payloadList = []
                    payloadList.append(payload)
                    
                except Exception as e:
                    logging.debug('Error while getting response for message id:- '+ msgId)
                    traceback.print_exc()
                    continue
                
                
            
        jsonObj = json.dumps([dict(pn) for pn in payloadList])
        pushpostrequest = urllib2.Request("http://localhost:3001/addPushNotification")
        pushpostrequest.add_header('Content-Type', 'application/json')
        response = urllib2.urlopen(pushpostrequest, jsonObj).read()
        
        logging.debug('Total Sms Sent:- '+str(len(sentSmsUsers)))
        
        notificationCampaign.smsprocessed = True
        session.commit()
        
    logging.debug('SMS Blaster Process Completed.....'+str(datetime.now()))
                  

if __name__=='__main__':
    main()
    try:
        session.close()
    except:
        print 'Error while closing session'