Subversion Repositories SmartDukaan

Rev

Rev 17228 | Rev 17235 | 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))
15691 manish.sha 121
 
122
            data = {"message":notificationRecord.message,"cid":notificationRecord.campaignId,"title":notificationRecord.title,
123
                    "type":notificationRecord.type,"url":notificationRecord.url,"vibrate":1,"sound":1,"largeIcon":"large_icon",
16386 manish.sha 124
                    "smallIcon":"small_icon","priority":"high","time_to_live":long(time.mktime(notificationRecord.expiresAt.timetuple()))-long(time.mktime(datetime.datetime.now().timetuple()))}
15691 manish.sha 125
 
126
            post_data = {}
127
 
128
            post_data['data'] = data
15724 manish.sha 129
            regIds = []
130
            regIds.append(notificationRecord.gcmRegId)
131
            post_data['registration_ids'] = regIds
15691 manish.sha 132
 
133
            post_data_json = json.dumps(post_data)
16294 manish.sha 134
            logging.debug('User Id:- '+str(notificationRecord.userId)+' Post Data Json :- '+str(post_data_json))
15691 manish.sha 135
 
136
            response = requests.post(GCM_URL, data=post_data_json, headers=headers)
16294 manish.sha 137
            logging.debug('User Id:- '+str(notificationRecord.userId)+' Response :-'+str(response.text))
15725 manish.sha 138
            result = json.loads(response.text)
15691 manish.sha 139
 
140
            if result["success"]:
17228 manish.sha 141
                update_params = { 'user_id' : notificationRecord.userId,  'notification_campaign_id' : notificationRecord.campaignId, 'type' : 'sent', 'status':1, 'message':'success' }
142
                encoded_update_params = urllib.urlencode(update_params)
143
                updateReq = urllib2.Request(PUSH_NOTIFICATIONS_UPDATE_URL+encoded_update_params)
144
                updateResponse = urllib2.urlopen(updateReq)
145
                response_str = updateResponse.read()
146
                logging.debug('User Id:- '+str(notificationRecord.userId)+' Update Response :-'+str(response_str))
15691 manish.sha 147
            else:
17228 manish.sha 148
                update_params = { 'user_id' : notificationRecord.userId,  'notification_campaign_id' : notificationRecord.campaignId, 'type' : 'sent', 'status':0, 'message':result["results"][0]["error"] }
149
                encoded_update_params = urllib.urlencode(update_params)
150
                updateReq = urllib2.Request(PUSH_NOTIFICATIONS_UPDATE_URL+encoded_update_params)
151
                updateResponse = urllib2.urlopen(updateReq)
152
                response_str = updateResponse.read()
153
                logging.debug('User Id:- '+str(notificationRecord.userId)+' Update Response :-'+str(response_str))
15691 manish.sha 154
 
155
                updateGcmUserSql = "update gcm_users set failurecount=failurecount+1 where gcm_regid='%s'"%(notificationRecord.gcmRegId)
15759 manish.sha 156
                logging.debug('Update GCM User Query :-'+str(updateGcmUserSql))
15691 manish.sha 157
                try:
15726 manish.sha 158
                    dtrdb = MySQLdb.connect('localhost',"root","shop2020","dtr" )
159
                    cursor = dtrdb.cursor()
15691 manish.sha 160
                    cursor.execute(updateGcmUserSql)
15726 manish.sha 161
                    dtrdb.commit()
15691 manish.sha 162
                    session.commit()
15726 manish.sha 163
                    dtrdb.close()
15691 manish.sha 164
                except:
15726 manish.sha 165
                    dtrdb.rollback()
166
                    dtrdb.close()
15759 manish.sha 167
            #time.sleep(2)
15691 manish.sha 168
 
169
def chunks(l, n):
170
    """Yield successive n-sized chunks from l."""
171
    for i in xrange(0, len(l), n):
172
        yield l[i:i+n]
173
 
174
def main():
17228 manish.sha 175
    global userGcmRegIdMap
176
    global campaignsMap
15691 manish.sha 177
    parser = optparse.OptionParser()
178
    parser.add_option("-C", "--chunksize", dest="chunksize",
179
                      default="100",
180
                      type="int", help="The requsets a single thread handles",
181
                      metavar="CHUNKSIZE")
182
    (options, args) = parser.parse_args()
183
 
17228 manish.sha 184
 
185
    notificationListReq = urllib2.Request(PENDING_PUSH_NOTIFICATION_URL)
186
    notificationListResponse = urllib2.urlopen(notificationListReq)
187
    notificationListJson = json.loads(notificationListResponse.read())
188
 
189
    usersList =[]
190
    campaignIdList = []
191
 
192
    for notificationRec in notificationListJson:
193
        if notificationRec.get('user_id') not in usersList:
194
            usersList.append(notificationRec.get('user_id'))
195
        if notificationRec.get('notification_campaign_id') not in campaignIdList:
196
            campaignIdList.append(notificationRec.get('notification_campaign_id'))
197
 
198
    usersList.append(0)
199
    campaignIdList.append(0)
15691 manish.sha 200
 
17229 manish.sha 201
    if len(usersList) >1 and len(campaignIdList)>1:
202
        cursor.execute(GCM_REG_ID_SQL%(str(tuple(usersList))))
203
        result_data = cursor.fetchall()
17228 manish.sha 204
 
17229 manish.sha 205
        for dataRec in result_data:
206
            userGcmRegIdMap[dataRec[0]] = dataRec[1]
15691 manish.sha 207
 
17229 manish.sha 208
        cursor.execute(CAMPAIGNS_SQL%(str(tuple(campaignIdList))))
209
        campaign_data = cursor.fetchall()
210
 
211
        for campaignRec in campaign_data:
212
            campaignsMap[campaignRec[0]] = campaignRec    
213
 
214
        count = 1
215
        if result_data:
216
            campaign_receivers_list = list(chunks(notificationListJson, options.chunksize))
217
            print len(campaign_receivers_list)
218
            for sublist in campaign_receivers_list:
219
                thread = NotificationThread(count, "Thread-"+str(count), sublist)
220
                thread.start()
221
                count = count +1
222
 
15691 manish.sha 223
    db.close()
224
 
225
if __name__=='__main__':
226
    main()
227