Subversion Repositories SmartDukaan

Rev

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