Subversion Repositories SmartDukaan

Rev

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