Subversion Repositories SmartDukaan

Rev

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