Subversion Repositories SmartDukaan

Rev

Rev 15727 | Rev 16294 | Go to most recent revision | Show entire file | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

Rev 15727 Rev 15759
Line 16... Line 16...
16
import json
16
import json
17
import optparse
17
import optparse
18
import urllib2
18
import urllib2
19
import base64
19
import base64
20
import urllib
20
import urllib
-
 
21
import logging
21
 
22
 
22
GCM_URL = "https://android.googleapis.com/gcm/send"
23
GCM_URL = "https://android.googleapis.com/gcm/send"
23
GOOGLE_API_KEY = "AIzaSyDw1qBnmxtnfR9NqBewryQ-yo3cG2ravGM"
24
GOOGLE_API_KEY = "AIzaSyDw1qBnmxtnfR9NqBewryQ-yo3cG2ravGM"
24
headers = {'content-type':'application/json', "authorization":"key=" + GOOGLE_API_KEY}
25
headers = {'content-type':'application/json', "authorization":"key=" + GOOGLE_API_KEY}
25
aff_url_headers = { 
26
aff_url_headers = { 
Line 39... Line 40...
39
cursor.execute(ALL_STORES_SQL)
40
cursor.execute(ALL_STORES_SQL)
40
result_stores = cursor.fetchall()
41
result_stores = cursor.fetchall()
41
domainStoresMap = {}
42
domainStoresMap = {}
42
for rec in result_stores:
43
for rec in result_stores:
43
    domainStoresMap[rec[2]] = rec
44
    domainStoresMap[rec[2]] = rec
-
 
45
    
-
 
46
logging.basicConfig(level=logging.DEBUG,
-
 
47
                    format='[%(levelname)s] (%(threadName)-10s) %(message)s',
-
 
48
                    )
44
 
49
 
45
 
50
 
46
class NotificationRecord():
51
class NotificationRecord():
47
    pushNotificationId = None
52
    pushNotificationId = None
48
    userId = None
53
    userId = None
Line 77... Line 82...
77
        threading.Thread.__init__(self)
82
        threading.Thread.__init__(self)
78
        self.threadID = threadID
83
        self.threadID = threadID
79
        self.name = name
84
        self.name = name
80
        self.recordsList = recordsList
85
        self.recordsList = recordsList
81
    def run(self):
86
    def run(self):
-
 
87
        logging.debug('Starting')
82
        handleCampaignRequest(self.name, self.recordsList)
88
        handleCampaignRequest(self.name, self.recordsList)
-
 
89
        logging.debug('Completed')
83
 
90
 
84
def handleCampaignRequest(threadName, recordsList ):
91
def handleCampaignRequest(threadName, recordsList ):
85
    for record in recordsList:
92
    for record in recordsList:
86
        notificationRecord = NotificationRecord(record[0], record[1], record[2], record[3], record[4], record[5], record[6], record[7], record[9], record[10], record[11], record[12])
93
        notificationRecord = NotificationRecord(record[0], record[1], record[2], record[3], record[4], record[5], record[6], record[7], record[9], record[10], record[11], record[12])
87
        if notificationRecord.type=='url':
94
        if notificationRecord.type=='url':
88
            parsed_uri = urlparse(notificationRecord.url)
95
            parsed_uri = urlparse(notificationRecord.url)
89
            domain = '{uri.netloc}'.format(uri=parsed_uri)
96
            domain = '{uri.netloc}'.format(uri=parsed_uri)
90
            print domain
97
            logging.debug('Affiliate Domain:-'+str(domain))
-
 
98
            logging.debug('User Id:-'+str(notificationRecord.userId)+' And GCM Reg Id:- '+ str(notificationRecord.gcmRegId))
91
            store = domainStoresMap.get(domain)
99
            store = domainStoresMap.get(domain)
92
            if store is not None:
100
            if store is not None:
93
                url_params = { 'url' : notificationRecord.url,  'userId' : notificationRecord.userId, 'storeId' : store[0] }
101
                url_params = { 'url' : notificationRecord.url,  'userId' : notificationRecord.userId, 'storeId' : store[0] }
94
                encoded_url_params = urllib.urlencode(url_params)
102
                encoded_url_params = urllib.urlencode(url_params)
95
                
103
                
Line 110... Line 118...
110
            regIds = []
118
            regIds = []
111
            regIds.append(notificationRecord.gcmRegId)
119
            regIds.append(notificationRecord.gcmRegId)
112
            post_data['registration_ids'] = regIds
120
            post_data['registration_ids'] = regIds
113
             
121
             
114
            post_data_json = json.dumps(post_data)
122
            post_data_json = json.dumps(post_data)
115
            print post_data_json
123
            logging.debug('Post Data Json :-'+str(post_data_json))
116
            
124
            
117
            response = requests.post(GCM_URL, data=post_data_json, headers=headers)
125
            response = requests.post(GCM_URL, data=post_data_json, headers=headers)
118
            print response.text
126
            logging.debug('Response :-'+str(response.text))
119
            result = json.loads(response.text)
127
            result = json.loads(response.text)
120
            pushnotification = Pushnotifications.get_by(id=notificationRecord.pushNotificationId)
128
            pushnotification = Pushnotifications.get_by(id=notificationRecord.pushNotificationId)
121
            
129
            
122
            if result["success"]:
130
            if result["success"]:
123
                pushnotification.type = "sent"
131
                pushnotification.type = "sent"
Line 128... Line 136...
128
                pushnotification.type = "sent"
136
                pushnotification.type = "sent"
129
                pushnotification.status = False
137
                pushnotification.status = False
130
                pushnotification.message = result["results"][0]["error"]
138
                pushnotification.message = result["results"][0]["error"]
131
                
139
                
132
                updateGcmUserSql = "update gcm_users set failurecount=failurecount+1 where gcm_regid='%s'"%(notificationRecord.gcmRegId)
140
                updateGcmUserSql = "update gcm_users set failurecount=failurecount+1 where gcm_regid='%s'"%(notificationRecord.gcmRegId)
133
                print updateGcmUserSql
141
                logging.debug('Update GCM User Query :-'+str(updateGcmUserSql))
134
                try:
142
                try:
135
                    dtrdb = MySQLdb.connect('localhost',"root","shop2020","dtr" )
143
                    dtrdb = MySQLdb.connect('localhost',"root","shop2020","dtr" )
136
                    cursor = dtrdb.cursor()
144
                    cursor = dtrdb.cursor()
137
                    cursor.execute(updateGcmUserSql)
145
                    cursor.execute(updateGcmUserSql)
138
                    dtrdb.commit()
146
                    dtrdb.commit()
139
                    session.commit()
147
                    session.commit()
140
                    dtrdb.close()
148
                    dtrdb.close()
141
                except:
149
                except:
142
                    dtrdb.rollback()
150
                    dtrdb.rollback()
143
                    dtrdb.close()
151
                    dtrdb.close()
-
 
152
            #time.sleep(2)
144
 
153
 
145
def chunks(l, n):
154
def chunks(l, n):
146
    """Yield successive n-sized chunks from l."""
155
    """Yield successive n-sized chunks from l."""
147
    for i in xrange(0, len(l), n):
156
    for i in xrange(0, len(l), n):
148
        yield l[i:i+n]
157
        yield l[i:i+n]