Subversion Repositories SmartDukaan

Rev

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

Rev Author Line No. Line
15691 manish.sha 1
#!/usr/bin/python
2
 
3
import threading
4
import time
16386 manish.sha 5
import datetime
15691 manish.sha 6
 
7
import MySQLdb
8
from elixir import *
9
from sqlalchemy.orm.exc import NoResultFound, MultipleResultsFound
10
from sqlalchemy.sql import func
11
from sqlalchemy.sql.expression import and_, or_, desc, not_, distinct, cast, \
12
    between
13
from urlparse import urlparse
14
import requests
15
import json
16
import optparse
17
import urllib2
18
import base64
19
import urllib
15759 manish.sha 20
import logging
17228 manish.sha 21
from dtr.utils.utils import get_mongo_connection
15691 manish.sha 22
 
23
GCM_URL = "https://android.googleapis.com/gcm/send"
24
GOOGLE_API_KEY = "AIzaSyDw1qBnmxtnfR9NqBewryQ-yo3cG2ravGM"
17228 manish.sha 25
PENDING_PUSH_NOTIFICATION_URL = "http://45.33.50.227:3001/getPendingNotifications"
26
PUSH_NOTIFICATIONS_UPDATE_URL = "http://45.33.50.227:3001/updatePushNotification/?"
15691 manish.sha 27
headers = {'content-type':'application/json', "authorization":"key=" + GOOGLE_API_KEY}
28
aff_url_headers = { 
29
            'User-agent':'Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36',
30
            'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',      
31
            'Accept-Language' : 'en-US,en;q=0.8',                     
32
            'Accept-Charset' : 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
33
            'Connection':'keep-alive'
34
        }
35
 
36
db = MySQLdb.connect('localhost',"root","shop2020","dtr" )
37
cursor = db.cursor()
17228 manish.sha 38
userGcmRegIdMap = {}
39
campaignsMap = {}
15691 manish.sha 40
 
41
ALL_STORES_SQL = "select * from stores"
17228 manish.sha 42
GCM_REG_ID_SQL = "select x.user_id, x.gcm_regid from (select * from gcm_users where user_id in %s order by id desc) as x group by x.user_id"
43
CAMPAIGNS_SQL = "select * from notification_campaigns where id in %s order by id"
15691 manish.sha 44
 
17228 manish.sha 45
 
15691 manish.sha 46
cursor.execute(ALL_STORES_SQL)
47
result_stores = cursor.fetchall()
48
domainStoresMap = {}
49
for rec in result_stores:
50
    domainStoresMap[rec[2]] = rec
15759 manish.sha 51
 
52
logging.basicConfig(level=logging.DEBUG,
53
                    format='[%(levelname)s] (%(threadName)-10s) %(message)s',
54
                    )
15691 manish.sha 55
 
56
 
57
class NotificationRecord():
58
    pushNotificationId = None
59
    userId = None
60
    campaignId = None
61
    campaignName = None
62
    title = None
63
    message= None
64
    type = None
65
    url = None
66
    expiresAt = None
67
    notificationStatus = None
68
    notificationCreated = None
69
    gcmRegId = None
70
 
71
    def __init__(self,pushNotificationId, userId, campaignId, campaignName, title, message, type, url, expiresAt, notificationStatus, notificationCreated, gcmRegId):
72
        self.pushNotificationId = pushNotificationId
73
        self.userId = userId
74
        self.campaignId = campaignId
75
        self.campaignName = campaignName
76
        self.title = title
77
        self.message= message
78
        self.type = type
79
        self.url = url
80
        self.expiresAt = expiresAt
81
        self.notificationStatus = notificationStatus
82
        self.notificationCreated = notificationCreated
83
        self.gcmRegId = gcmRegId
84
 
85
 
86
class NotificationThread (threading.Thread):
87
    def __init__(self, threadID, name, recordsList):
88
        threading.Thread.__init__(self)
89
        self.threadID = threadID
90
        self.name = name
91
        self.recordsList = recordsList
92
    def run(self):
15759 manish.sha 93
        logging.debug('Starting')
15691 manish.sha 94
        handleCampaignRequest(self.name, self.recordsList)
15759 manish.sha 95
        logging.debug('Completed')
15691 manish.sha 96
 
97
def handleCampaignRequest(threadName, recordsList ):
98
    for record in recordsList:
17228 manish.sha 99
        campaignRecord = campaignsMap.get(record.get('notification_campaign_id'))
100
        notificationRecord = NotificationRecord(record.get('_id'), record.get('user_id'), record.get('notification_campaign_id'), campaignRecord[1], campaignRecord[2], campaignRecord[3], campaignRecord[4], campaignRecord[5], campaignRecord[7], campaignRecord[8], campaignRecord[9], userGcmRegIdMap.get(record.get('user_id')))
15691 manish.sha 101
        if notificationRecord.type=='url':
102
            parsed_uri = urlparse(notificationRecord.url)
103
            domain = '{uri.netloc}'.format(uri=parsed_uri)
15759 manish.sha 104
            logging.debug('Affiliate Domain:-'+str(domain))
105
            logging.debug('User Id:-'+str(notificationRecord.userId)+' And GCM Reg Id:- '+ str(notificationRecord.gcmRegId))
15691 manish.sha 106
            store = domainStoresMap.get(domain)
107
            if store is not None:
108
                url_params = { 'url' : notificationRecord.url,  'userId' : notificationRecord.userId, 'storeId' : store[0] }
109
                encoded_url_params = urllib.urlencode(url_params)
110
 
111
                DTR_API_BASIC_AUTH = base64.encodestring('%s:%s' % ("dtr", "dtr18Feb2015")).replace('\n', '')
112
 
113
                pushpostrequest = urllib2.Request('http://api.profittill.com/pushnotifications/generateAffiliateUrl', encoded_url_params, headers=aff_url_headers)
114
                pushpostrequest.add_header("Authorization", "Basic %s" % DTR_API_BASIC_AUTH)
115
                json_result =  json.loads(urllib2.urlopen(pushpostrequest).read())
116
                notificationRecord.url = json_result['url']
16294 manish.sha 117
                logging.debug('User Id:-'+str(notificationRecord.userId)+' Notification Url:- '+ str(notificationRecord.url))
16295 manish.sha 118
            else:
119
                notificationRecord.url = notificationRecord.url+'?user_id='+str(notificationRecord.userId)
16350 manish.sha 120
                logging.debug('User Id:-'+str(notificationRecord.userId)+' Notification Url:- '+ str(notificationRecord.url))
17235 manish.sha 121
        if notificationRecord.url is None or str(notificationRecord.url)=='':
122
            notificationRecord.url = 'http://api.profittill.com/deals?user_id='+str(notificationRecord.userId)
123
        data = {"message":notificationRecord.message,"cid":notificationRecord.campaignId,"title":notificationRecord.title,
124
                "type":notificationRecord.type,"url":notificationRecord.url,"vibrate":1,"sound":1,"largeIcon":"large_icon",
125
                "smallIcon":"small_icon","priority":"high","time_to_live":long(time.mktime(notificationRecord.expiresAt.timetuple()))-long(time.mktime(datetime.datetime.now().timetuple()))}
126
 
127
        post_data = {}
128
 
129
        post_data['data'] = data
130
        regIds = []
131
        regIds.append(notificationRecord.gcmRegId)
132
        post_data['registration_ids'] = regIds
133
 
134
        post_data_json = json.dumps(post_data)
135
        logging.debug('User Id:- '+str(notificationRecord.userId)+' Post Data Json :- '+str(post_data_json))
136
 
137
        response = requests.post(GCM_URL, data=post_data_json, headers=headers)
138
        logging.debug('User Id:- '+str(notificationRecord.userId)+' Response :-'+str(response.text))
139
        result = json.loads(response.text)
140
 
141
        if result["success"]:
142
            update_params = { 'user_id' : notificationRecord.userId,  'notification_campaign_id' : notificationRecord.campaignId, 'type' : 'sent', 'status':1, 'message':'success' }
143
            encoded_update_params = urllib.urlencode(update_params)
144
            updateReq = urllib2.Request(PUSH_NOTIFICATIONS_UPDATE_URL+encoded_update_params)
145
            updateResponse = urllib2.urlopen(updateReq)
146
            response_str = updateResponse.read()
147
            logging.debug('User Id:- '+str(notificationRecord.userId)+' Update Response :-'+str(response_str))
148
        else:
149
            update_params = { 'user_id' : notificationRecord.userId,  'notification_campaign_id' : notificationRecord.campaignId, 'type' : 'sent', 'status':0, 'message':result["results"][0]["error"] }
150
            encoded_update_params = urllib.urlencode(update_params)
151
            updateReq = urllib2.Request(PUSH_NOTIFICATIONS_UPDATE_URL+encoded_update_params)
152
            updateResponse = urllib2.urlopen(updateReq)
153
            response_str = updateResponse.read()
154
            logging.debug('User Id:- '+str(notificationRecord.userId)+' Update Response :-'+str(response_str))
15691 manish.sha 155
 
17235 manish.sha 156
            updateGcmUserSql = "update gcm_users set failurecount=failurecount+1 where gcm_regid='%s'"%(notificationRecord.gcmRegId)
157
            logging.debug('Update GCM User Query :-'+str(updateGcmUserSql))
158
            try:
159
                dtrdb = MySQLdb.connect('localhost',"root","shop2020","dtr" )
160
                cursor = dtrdb.cursor()
161
                cursor.execute(updateGcmUserSql)
162
                dtrdb.commit()
163
                session.commit()
164
                dtrdb.close()
165
            except:
166
                dtrdb.rollback()
167
                dtrdb.close()
15759 manish.sha 168
            #time.sleep(2)
15691 manish.sha 169
 
170
def chunks(l, n):
171
    """Yield successive n-sized chunks from l."""
172
    for i in xrange(0, len(l), n):
173
        yield l[i:i+n]
174
 
175
def main():
17228 manish.sha 176
    global userGcmRegIdMap
177
    global campaignsMap
15691 manish.sha 178
    parser = optparse.OptionParser()
179
    parser.add_option("-C", "--chunksize", dest="chunksize",
180
                      default="100",
181
                      type="int", help="The requsets a single thread handles",
182
                      metavar="CHUNKSIZE")
183
    (options, args) = parser.parse_args()
184
 
17228 manish.sha 185
 
186
    notificationListReq = urllib2.Request(PENDING_PUSH_NOTIFICATION_URL)
187
    notificationListResponse = urllib2.urlopen(notificationListReq)
188
    notificationListJson = json.loads(notificationListResponse.read())
189
 
190
    usersList =[]
191
    campaignIdList = []
192
 
193
    for notificationRec in notificationListJson:
194
        if notificationRec.get('user_id') not in usersList:
195
            usersList.append(notificationRec.get('user_id'))
196
        if notificationRec.get('notification_campaign_id') not in campaignIdList:
197
            campaignIdList.append(notificationRec.get('notification_campaign_id'))
198
 
199
    usersList.append(0)
200
    campaignIdList.append(0)
17235 manish.sha 201
    logging.debug('Starting Push Notification Job....'+str(datetime.datetime.now()))
15691 manish.sha 202
 
17229 manish.sha 203
    if len(usersList) >1 and len(campaignIdList)>1:
204
        cursor.execute(GCM_REG_ID_SQL%(str(tuple(usersList))))
205
        result_data = cursor.fetchall()
17228 manish.sha 206
 
17229 manish.sha 207
        for dataRec in result_data:
208
            userGcmRegIdMap[dataRec[0]] = dataRec[1]
15691 manish.sha 209
 
17229 manish.sha 210
        cursor.execute(CAMPAIGNS_SQL%(str(tuple(campaignIdList))))
211
        campaign_data = cursor.fetchall()
212
 
213
        for campaignRec in campaign_data:
214
            campaignsMap[campaignRec[0]] = campaignRec    
215
 
216
        count = 1
217
        if result_data:
218
            campaign_receivers_list = list(chunks(notificationListJson, options.chunksize))
219
            print len(campaign_receivers_list)
220
            for sublist in campaign_receivers_list:
221
                thread = NotificationThread(count, "Thread-"+str(count), sublist)
222
                thread.start()
223
                count = count +1
17235 manish.sha 224
 
225
    logging.debug('Stopping Push Notification Job....'+str(datetime.datetime.now()))
17229 manish.sha 226
 
15691 manish.sha 227
    db.close()
228
 
229
if __name__=='__main__':
230
    main()
231