Subversion Repositories SmartDukaan

Rev

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

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