Subversion Repositories SmartDukaan

Rev

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