Subversion Repositories SmartDukaan

Rev

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

import MySQLdb
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
import optparse
import urllib2
import base64
import urllib
import logging
from dtr.utils.utils import get_mongo_connection, to_java_date, num_encode
from datetime import datetime, timedelta
from dtr.storage import DataService
from dtr.storage.DataService import Users
import traceback
import time

DataService.initialize(db_hostname="192.168.158.89")
logging.basicConfig(level=logging.DEBUG)
mongoHost = 'localhost'

def main():
    global mongoHost
    parser = 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_host
    timeCondition = datetime.now()-timedelta(hours=2)
    eligibleSmsNotficationCampaigns = list(get_mongo_connection(host=mongoHost).User.notificationcampaigns.find({'smsprocessed':1,'created':{'$lte':to_java_date(timeCondition)}}))
    for notificationCampaign in eligibleSmsNotficationCampaigns:
        logging.debug('Notification_Campign_Id:- '+str(notificationCampaign.get('_id')))
        
        jsonSentList = list(get_mongo_connection(host=mongoHost).User.pushnotificationsnew.find({'notification_campaign_id':notificationCampaign.get('_id'),'smstype':'SMS_SENT_OPERATOR'}))
        logging.debug('Total Promotional Entries to Processed.....'+str(len(jsonSentList))+' Current Time:- '+str(datetime.now()))
        
        for smsResponse in jsonSentList:
            del_det_params = {'user' : 'srlsaholicP', 'password' : 'srp8oct' , 'apimsgid' : smsResponse.get('sms_id')}
            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('User Id:- '+str(smsResponse.get('user_id'))+ ' Delivery Report Url:- '+del_det_url)
            
            try:
                status = ""
                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
                
                get_mongo_connection(host=mongoHost).User.pushnotificationsnew.update({'_id':smsResponse.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:- '+ str(smsResponse.get("sms_id")))
                traceback.print_exc()
                continue
        
        jsonSentList = list(get_mongo_connection(host=mongoHost).User.pushnotificationsnew.find({'notification_campaign_id':notificationCampaign.get('_id'),'smstype':'SMS_INPROCESS'}))
        logging.debug('Total Transactional Entries to Processed.....'+str(len(jsonSentList))+' Current Time:- '+str(datetime.now()))
        
        for smsResponse in jsonSentList:
            del_det_params = {'uname' : 'srlsaholic', 'passwd' : 'sr18mar' , 'messageid' : str(smsResponse.get('sms_id'))}
            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('User Id:- '+str(smsResponse.get('user_id'))+ ' 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'
                
                get_mongo_connection(host=mongoHost).User.pushnotificationsnew.update({'_id':smsResponse.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:- '+ str(smsResponse.get("sms_id")))
                traceback.print_exc()
                continue          

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