Subversion Repositories SmartDukaan

Rev

Rev 17377 | Rev 17400 | Go to most recent revision | Show entire file | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

Rev 17377 Rev 17398
Line 13... Line 13...
13
import urllib
13
import urllib
14
import urllib2
14
import urllib2
15
import json
15
import json
16
import time
16
import time
17
import traceback
17
import traceback
-
 
18
import logging
18
 
19
 
19
PUSH_NOTIFICATIONS_DETAILS_URL="http://45.33.50.227:3001/getPushNotificationDetailsByType/?type=%s&notification_campaign_id=%d&status=%s"
20
PUSH_NOTIFICATIONS_DETAILS_URL="http://45.33.50.227:3001/getPushNotificationDetailsByType/?type=%s&notification_campaign_id=%d&status=%s"
20
PROMOTIONAL_SMS_SEND_URL = "http://103.15.179.45:8085/MessagingGateway/SendTransSMS?"
21
PROMOTIONAL_SMS_SEND_URL = "http://103.15.179.45:8085/MessagingGateway/SendTransSMS?"
21
#ID is: PRO02135496 Mobile Number is: 918512809859 PRO02135496#SMS Sent successfully to : 918512809859
22
#ID is: PRO02135496 Mobile Number is: 918512809859 PRO02135496#SMS Sent successfully to : 918512809859
22
#http://103.15.179.45:8085/MessagingGateway/http/querymsg?user=srlsaholicP&password=srp8oct&apimsgid=PRO02257518
23
#http://103.15.179.45:8085/MessagingGateway/http/querymsg?user=srlsaholicP&password=srp8oct&apimsgid=PRO02257518
23
#MessageID: PRO02135496 STATUS: DELIVRD ErrorCode: 0 DR Time: 2015-10-20 18:05:11 
24
#MessageID: PRO02135496 STATUS: DELIVRD ErrorCode: 0 DR Time: 2015-10-20 18:05:11 
24
 
25
 
25
DataService.initialize(db_hostname="192.168.158.89")
26
DataService.initialize(db_hostname="192.168.158.89")
26
 
27
 
-
 
28
logging.basicConfig(level=logging.DEBUG)
-
 
29
 
27
def main():
30
def main():
-
 
31
    logging.debug('Starting SMS Blaster Process.....'+str(datetime.datetime.now()))
28
    timeCondition = datetime.now()-timedelta(hours=2)
32
    timeCondition = datetime.now()-timedelta(hours=2)
29
    expireTimeCondition = datetime.now()+timedelta(hours=2)
33
    expireTimeCondition = datetime.now()+timedelta(hours=2)
30
    eligibleSmsNotficationCampaigns = notification_campaigns.query.filter(notification_campaigns.sendsms==True).filter(notification_campaigns.smsprocessed==False).filter(notification_campaigns.created<timeCondition).filter(notification_campaigns.expiresat>expireTimeCondition).all()
34
    eligibleSmsNotficationCampaigns = notification_campaigns.query.filter(notification_campaigns.sendsms==True).filter(notification_campaigns.smsprocessed==False).filter(notification_campaigns.created<timeCondition).filter(notification_campaigns.expiresat>expireTimeCondition).all()
31
    #eligibleSmsNotficationCampaigns = notification_campaigns.query.filter(notification_campaigns.id==5417).all()
35
    #eligibleSmsNotficationCampaigns = notification_campaigns.query.filter(notification_campaigns.id==5417).all()
32
    
36
    
33
    for notificationCampaign in eligibleSmsNotficationCampaigns:
37
    for notificationCampaign in eligibleSmsNotficationCampaigns:
34
        print notificationCampaign.id
38
        logging.debug('Notification_Campign_Id:- '+str(notificationCampaign.id))
35
        sentFailedresponse = urllib2.urlopen(PUSH_NOTIFICATIONS_DETAILS_URL%('sent',notificationCampaign.id,0)).read()
39
        sentFailedresponse = urllib2.urlopen(PUSH_NOTIFICATIONS_DETAILS_URL%('sent',notificationCampaign.id,0)).read()
36
        jsonList = json.loads(sentFailedresponse)
40
        jsonList = json.loads(sentFailedresponse)
37
        userList = []
41
        userList = []
38
        for obj in jsonList:
42
        for obj in jsonList:
39
            userList.append(long(obj.get('user_id')))
43
            userList.append(long(obj.get('user_id')))
40
        print 'Failed User List',len(userList)
44
        logging.debug('Failed User List...'+str(len(userList)))
41
            
45
            
42
        sentSuccessResponse = urllib2.urlopen(PUSH_NOTIFICATIONS_DETAILS_URL%('sent',notificationCampaign.id,1)).read()
46
        sentSuccessResponse = urllib2.urlopen(PUSH_NOTIFICATIONS_DETAILS_URL%('sent',notificationCampaign.id,1)).read()
43
        jsonList = json.loads(sentSuccessResponse)
47
        jsonList = json.loads(sentSuccessResponse)
44
        for obj in jsonList:
48
        for obj in jsonList:
45
            userList.append(long(obj.get('user_id')))
49
            userList.append(long(obj.get('user_id')))
46
        
50
        
47
        userList = list(set(userList))
51
        userList = list(set(userList))
48
          
52
          
49
        receivedSuccessResponse = urllib2.urlopen(PUSH_NOTIFICATIONS_DETAILS_URL%('recieved',notificationCampaign.id,1)).read()
53
        receivedSuccessResponse = urllib2.urlopen(PUSH_NOTIFICATIONS_DETAILS_URL%('recieved',notificationCampaign.id,1)).read()
50
        jsonList = json.loads(receivedSuccessResponse)
54
        jsonList = json.loads(receivedSuccessResponse)
51
        print 'User List Before',len(userList)
55
        logging.debug('User List Before...'+str(len(userList)))
52
        for obj in jsonList:
56
        for obj in jsonList:
53
            if obj.get('user_id') in userList:
57
            if obj.get('user_id') in userList:
54
                userList.remove(long(obj.get('user_id')))
58
                userList.remove(long(obj.get('user_id')))
55
        print 'User List After',len(userList)
59
        logging.debug('User List After...'+str(len(userList)))
56
        
60
        
57
        allUsers = Users.query.filter(Users.id.in_(tuple(userList))).all()
61
        allUsers = Users.query.filter(Users.id.in_(tuple(userList))).all()
58
        #print allUsers
62
        #print allUsers
59
        
63
        
60
        sentSmsUsers = []
64
        sentSmsUsers = []
Line 65... Line 69...
65
        for user in allUsers:
69
        for user in allUsers:
66
            if user.mobile_number is not None and len(user.mobile_number)==10 and user.mobile_number not in sentSmsUsers:
70
            if user.mobile_number is not None and len(user.mobile_number)==10 and user.mobile_number not in sentSmsUsers:
67
                #url_params = { 'Mobile' : '91'+user.mobile_number,  'Username' : 'srlsaholicP', 'Password' : 'srp8oct' , 'MessageType' : 'txt', 'SenderID' : '090000', 'Message' : notificationCampaign.messagetext }
71
                #url_params = { 'Mobile' : '91'+user.mobile_number,  'Username' : 'srlsaholicP', 'Password' : 'srp8oct' , 'MessageType' : 'txt', 'SenderID' : '090000', 'Message' : notificationCampaign.messagetext }
68
                url_params = { 'Mobile' : '91'+user.mobile_number,  'Username' : 'srlsaholicP', 'Password' : 'srp8oct' , 'MessageType' : 'txt', 'SenderID' : '090000', 'Message' : smstext }
72
                url_params = { 'Mobile' : '91'+user.mobile_number,  'Username' : 'srlsaholicP', 'Password' : 'srp8oct' , 'MessageType' : 'txt', 'SenderID' : '090000', 'Message' : smstext }
69
                encoded_url_params = urllib.urlencode(url_params)
73
                encoded_url_params = urllib.urlencode(url_params)
-
 
74
                logging.debug('User Id:- '+str(user.id)+' Notification_Campaign_Id:- '+ str(notificationCampaign.id)+' Url Params:- '+str(encoded_url_params))
70
                url = PROMOTIONAL_SMS_SEND_URL + encoded_url_params
75
                url = PROMOTIONAL_SMS_SEND_URL + encoded_url_params
71
                print url
-
 
72
                response_str = None
76
                response_str = None
73
                try:
77
                try:
74
                    req = urllib2.Request(url)
78
                    req = urllib2.Request(url)
75
                    response = urllib2.urlopen(req)
79
                    response = urllib2.urlopen(req)
76
                    response_str = response.read()
80
                    response_str = response.read()
77
                except Exception as e:
81
                except Exception as e:
78
                    print 'Error while getting response for user id:- '+ str(user.id) +' Mobile Number:- '+str(user.mobile_number)
82
                    logging.debug('Error while getting response for user id:- '+ str(user.id) +' Mobile Number:- '+str(user.mobile_number))
79
                    traceback.print_exc()
83
                    traceback.print_exc()
80
                    continue
84
                    continue
81
                    
85
                    
82
                print response_str
86
                logging.debug('User Id:- '+str(user.id)+' Notification_Campaign_Id:- '+ str(notificationCampaign.id)+' Sent Response:- '+ str(response_str))
83
                
87
                
84
                
88
                
85
                payload = {}
89
                payload = {}
86
                payload["user_id"]= user.id
90
                payload["user_id"]= user.id
87
                payload["type"]="smssent"
91
                payload["type"]="smssent"
88
                payload["notification_campaign_id"]= notificationCampaign.id
92
                payload["notification_campaign_id"]= notificationCampaign.id
89
                payload["status"]=1
93
                payload["status"]=1
90
                
94
                
91
                if len(payloadList)==5000:
95
                if len(payloadList)==5000:
92
                    jsonObj = json.dumps([dict(pn) for pn in payloadList])
96
                    jsonObj = json.dumps([dict(pn) for pn in payloadList])
93
                    print jsonObj
-
 
94
                    pushpostrequest = urllib2.Request("http://45.33.50.227:3001/addPushNotification")
97
                    pushpostrequest = urllib2.Request("http://45.33.50.227:3001/addPushNotification")
95
                    pushpostrequest.add_header('Content-Type', 'application/json')
98
                    pushpostrequest.add_header('Content-Type', 'application/json')
96
                    response = urllib2.urlopen(pushpostrequest, jsonObj).read()
99
                    response = urllib2.urlopen(pushpostrequest, jsonObj).read()
97
                    payloadList = []
100
                    payloadList = []
98
                
101
                
Line 112... Line 115...
112
                    payload["notification_campaign_id"]= notificationCampaign.id
115
                    payload["notification_campaign_id"]= notificationCampaign.id
113
                    payload["status"]=1
116
                    payload["status"]=1
114
                    
117
                    
115
                    
118
                    
116
                    response_vals = response_str.split('\n')
119
                    response_vals = response_str.split('\n')
-
 
120
                    logging.debug('Desired Response String:- '+str(response_vals[2]))
117
                    if len(response_vals)==4 and 'SMS Sent successfully to' in response_vals[2]:
121
                    if len(response_vals)==4 and 'SMS Sent successfully to' in response_vals[2]:
118
                        if response_vals[2].split('#')[0]!='null':
122
                        if response_vals[2].split('#')[0]!='null':
119
                            smsResponseIdMap[user.id] = response_vals[2].split('#')[0]
123
                            smsResponseIdMap[user.id] = response_vals[2].split('#')[0]
120
                            payload["sms_id"]=response_vals[2].split('#')[0]
124
                            payload["sms_id"]=response_vals[2].split('#')[0]
121
                            payloadList.append(payload)
125
                            payloadList.append(payload)
Line 126... Line 130...
126
        for userId, msgId in smsResponseIdMap.items():
130
        for userId, msgId in smsResponseIdMap.items():
127
            #http://103.15.179.45:8085/MessagingGateway/http/querymsg?user=srlsaholicP&password=srp8oct&apimsgid=PRO02257518
131
            #http://103.15.179.45:8085/MessagingGateway/http/querymsg?user=srlsaholicP&password=srp8oct&apimsgid=PRO02257518
128
            del_det_params = {'user' : 'srlsaholicP', 'password' : 'srp8oct' , 'apimsgid' : msgId}
132
            del_det_params = {'user' : 'srlsaholicP', 'password' : 'srp8oct' , 'apimsgid' : msgId}
129
            encoded_del_det_params = urllib.urlencode(del_det_params)
133
            encoded_del_det_params = urllib.urlencode(del_det_params)
130
            del_det_url = 'http://103.15.179.45:8085/MessagingGateway/http/querymsg?' + encoded_del_det_params
134
            del_det_url = 'http://103.15.179.45:8085/MessagingGateway/http/querymsg?' + encoded_del_det_params
131
            print "Delivery Report Url-",del_det_url
135
            logging.debug('Delivery Report Url:- '+del_det_url)
132
            try:
136
            try:
133
                del_req = urllib2.Request(del_det_url)
137
                del_req = urllib2.Request(del_det_url)
134
                del_response = urllib2.urlopen(del_req)
138
                del_response = urllib2.urlopen(del_req)
135
                del_response_str = del_response.read()
139
                del_response_str = del_response.read()
136
                print del_response_str
140
                logging.debug('Delivery Report Response:- '+str(del_response_str))
137
                if 'STATUS' in del_response_str:
141
                if 'STATUS' in del_response_str:
138
                    status = del_response_str.split(' ')[3]
142
                    status = del_response_str.split(' ')[3]
139
                    if status=='DELIVRD':
143
                    if status=='DELIVRD':
140
                        status = 'SMS_DELIVRD'
144
                        status = 'SMS_DELIVRD'
141
                    elif status=='SENT':
145
                    elif status=='SENT':
Line 155... Line 159...
155
                    if status == 'SMS_SENT_OPERATOR':
159
                    if status == 'SMS_SENT_OPERATOR':
156
                        payload["sms_id"] = msgId
160
                        payload["sms_id"] = msgId
157
                    
161
                    
158
                    if len(payloadList)==5000:
162
                    if len(payloadList)==5000:
159
                        jsonObj = json.dumps([dict(pn) for pn in payloadList])
163
                        jsonObj = json.dumps([dict(pn) for pn in payloadList])
160
                        print jsonObj
-
 
161
                        pushpostrequest = urllib2.Request("http://45.33.50.227:3001/addPushNotification")
164
                        pushpostrequest = urllib2.Request("http://45.33.50.227:3001/addPushNotification")
162
                        pushpostrequest.add_header('Content-Type', 'application/json')
165
                        pushpostrequest.add_header('Content-Type', 'application/json')
163
                        response = urllib2.urlopen(pushpostrequest, jsonObj).read()
166
                        response = urllib2.urlopen(pushpostrequest, jsonObj).read()
164
                        payloadList = []
167
                        payloadList = []
165
                    payloadList.append(payload)
168
                    payloadList.append(payload)
166
                
169
                
167
            except Exception as e:
170
            except Exception as e:
168
                print 'Error while getting response for message id:- ', msgId
171
                logging.debug('Error while getting response for message id:- '+ msgId)
169
                traceback.print_exc()
172
                traceback.print_exc()
-
 
173
                continue
170
            
174
            
171
        jsonObj = json.dumps([dict(pn) for pn in payloadList])
175
        jsonObj = json.dumps([dict(pn) for pn in payloadList])
172
        pushpostrequest = urllib2.Request("http://45.33.50.227:3001/addPushNotification")
176
        pushpostrequest = urllib2.Request("http://45.33.50.227:3001/addPushNotification")
173
        pushpostrequest.add_header('Content-Type', 'application/json')
177
        pushpostrequest.add_header('Content-Type', 'application/json')
174
        response = urllib2.urlopen(pushpostrequest, jsonObj).read()
178
        response = urllib2.urlopen(pushpostrequest, jsonObj).read()
175
        
179
        
176
        print len(sentSmsUsers)
180
        logging.debug('Total Sms Sent:- '+str(len(sentSmsUsers)))
177
        
181
        
178
        notificationCampaign.smsprocessed = True
182
        notificationCampaign.smsprocessed = True
179
        session.commit()
183
        session.commit()
-
 
184
        
-
 
185
    logging.debug('SMS Blaster Process Completed.....'+str(datetime.datetime.now()))
180
                  
186
                  
181
 
187
 
182
if __name__=='__main__':
188
if __name__=='__main__':
183
    main()
189
    main()
184
    try:
190
    try: