Subversion Repositories SmartDukaan

Rev

Rev 19258 | Rev 22758 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
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:
79
                    url_params = { 'ani' : '91'+user.mobile_number,  'uname' : 'srlsaholic', 'passwd' : 'sr18mar' , 'cli' : 'PROFTM', 'message' : smstext.replace("TRAN_SMS", "").strip() }
80
                else:
81
                    url_params = { 'Mobile' : '91'+user.mobile_number,  'Username' : 'srlsaholicP', 'Password' : 'srp8oct' , 'MessageType' : 'txt', 'SenderID' : '090000', 'Message' : smstext }
82
                encoded_url_params = urllib.urlencode(url_params)
83
                logging.debug('User Id:- '+str(user.id)+' Notification_Campaign_Id:- '+ str(notificationCampaign.get('_id'))+' Url Params:- '+str(encoded_url_params))
84
                url = ''
85
                if "TRAN_SMS" in smstext:
86
                    url = TRANSACTIONAL_SMS_SEND_URL + encoded_url_params
87
                else:
88
                    url = PROMOTIONAL_SMS_SEND_URL + encoded_url_params
89
                response_str = None
90
                try:
91
                    req = urllib2.Request(url)
92
                    response = urllib2.urlopen(req)
93
                    response_str = response.read()
94
                except Exception as e:
95
                    logging.debug('Error while getting response for user id:- '+ str(user.id) +' Mobile Number:- '+str(user.mobile_number))
96
                    traceback.print_exc()
97
                    continue
98
 
99
                entry = smsToBeSentUsersMap.get(user.id)
100
                logging.debug('User Id:- '+str(user.id)+' Notification_Campaign_Id:- '+ str(notificationCampaign.get('_id'))+' Sent Response:- '+ str(response_str))
19258 manish.sha 101
                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 102
                if "TRAN_SMS" in smstext:
103
                    if "Message sent successfully to " in response_str:
104
                        response_str_vals = response_str.split('#')
19258 manish.sha 105
                        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 106
                        tranSmsResponseIdMap[user.id] = response_str_vals[0]
107
                    else:
19258 manish.sha 108
                        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 109
                else:
110
                    if "mobile no in DND" in response_str:
19258 manish.sha 111
                        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 112
                    else:
113
                        response_vals = response_str.split('\n')
114
                        logging.debug('Desired Response String:- '+str(response_vals[2]))
115
                        if len(response_vals)==4 and 'SMS Sent successfully to' in response_vals[2]:
116
                            if response_vals[2].split('#')[0]!='null':
117
                                proSmsResponseIdMap[user.id] = response_vals[2].split('#')[0]
19258 manish.sha 118
                                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 119
 
120
                sentSmsUsers.append(user.mobile_number)
121
 
122
        time.sleep(30)
123
 
124
        for userId, msgId in proSmsResponseIdMap.items():
125
            #http://103.15.179.45:8085/MessagingGateway/http/querymsg?user=srlsaholicP&password=srp8oct&apimsgid=PRO02257518
126
            del_det_params = {'user' : 'srlsaholicP', 'password' : 'srp8oct' , 'apimsgid' : msgId}
127
            encoded_del_det_params = urllib.urlencode(del_det_params)
128
            del_det_url = 'http://103.15.179.45:8085/MessagingGateway/http/querymsg?' + encoded_del_det_params
129
            logging.debug('Delivery Report Url:- '+del_det_url)
130
            try:
131
                del_req = urllib2.Request(del_det_url)
132
                del_response = urllib2.urlopen(del_req)
133
                del_response_str = del_response.read()
134
                logging.debug('Delivery Report Response:- '+str(del_response_str))
135
                if 'STATUS' in del_response_str:
136
                    status = del_response_str.split(' ')[3]
137
                    if status=='DELIVRD':
138
                        status = 'SMS_DELIVRD'
139
                    elif status=='SENT':
140
                        status = 'SMS_SENT_OPERATOR'
141
                    elif status=='REJECTD' or status== 'FAILED':
142
                        status = 'SMS_FAILED'
143
                    elif 'EXP_' in status:
144
                        status = 'SMS_EXPIRED'
145
                    else:
146
                        status = 'SMS_'+status
147
                entry = smsToBeSentUsersMap.get(userId)
19258 manish.sha 148
                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 149
            except Exception as e:
150
                logging.debug('Error while getting response for message id:- '+ msgId)
151
                traceback.print_exc()
152
                continue
153
 
154
 
155
        for userId, msgId in tranSmsResponseIdMap.items():
156
            status = ''
157
            if msgId == "No_Response":
158
                status = 'SMS_FAILED'
159
            else:
160
                del_det_params = {'uname' : 'srlsaholic', 'passwd' : 'sr18mar' , 'messageid' : msgId}
161
                encoded_del_det_params = urllib.urlencode(del_det_params)
162
                del_det_url = 'http://103.15.179.45:8085/SMSGateway/getApiReport?' + encoded_del_det_params
163
                logging.debug('Delivery Report Url:- '+del_det_url)
164
                try:
165
                    del_req = urllib2.Request(del_det_url)
166
                    del_response = urllib2.urlopen(del_req)
167
                    del_response_str = del_response.read()
168
                    logging.debug('Delivery Report Response:- '+str(del_response_str))
169
 
170
                    del_response_vals = del_response_str.split(' ')
171
 
172
                    status = ''
19753 manas 173
                    if len(del_response_vals) == 8 and del_response_vals[7][:-2] == '000':
19108 manish.sha 174
                        status = 'SMS_DELIVRD'
175
                    elif "Submitted to SMSC" in del_response_str:
176
                        status = 'SMS_INPROCESS'
177
                    else:
178
                        status = 'SMS_FAILED'
179
 
180
                except Exception as e:
181
                    logging.debug('Error while getting response for message id:- '+ msgId)
182
                    traceback.print_exc()
183
                    continue
184
 
19258 manish.sha 185
            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 186
 
187
        logging.debug('Total Sms Sent:- '+str(len(sentSmsUsers)))  
188
    logging.debug('SMS Blaster Process Completed.....'+str(datetime.now()))  
189
 
190
 
191
if __name__=='__main__':
192
    main()
193
    try:
194
        session.close()
195
    except:
196
        print 'Error while closing session'