Subversion Repositories SmartDukaan

Rev

Rev 15759 | Rev 16295 | 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
5
 
6
import MySQLdb
7
from dtr.storage import DataService
8
from dtr.storage.DataService import Pushnotifications
9
from elixir import *
10
from sqlalchemy.orm.exc import NoResultFound, MultipleResultsFound
11
from sqlalchemy.sql import func
12
from sqlalchemy.sql.expression import and_, or_, desc, not_, distinct, cast, \
13
    between
14
from urlparse import urlparse
15
import requests
16
import json
17
import optparse
18
import urllib2
19
import base64
20
import urllib
15759 manish.sha 21
import logging
15691 manish.sha 22
 
23
GCM_URL = "https://android.googleapis.com/gcm/send"
24
GOOGLE_API_KEY = "AIzaSyDw1qBnmxtnfR9NqBewryQ-yo3cG2ravGM"
25
headers = {'content-type':'application/json', "authorization":"key=" + GOOGLE_API_KEY}
26
aff_url_headers = { 
27
            'User-agent':'Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36',
28
            'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',      
29
            'Accept-Language' : 'en-US,en;q=0.8',                     
30
            'Accept-Charset' : 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
31
            'Connection':'keep-alive'
32
        }
33
 
34
db = MySQLdb.connect('localhost',"root","shop2020","dtr" )
35
cursor = db.cursor()
36
 
15727 manish.sha 37
PUSH_NOTIFICATIONS_SQL = "select p.id, p.user_id, n.*, g.gcm_regid from pushnotifications p join notification_campaigns n on p.notification_campaign_id = n.id left outer join (select * from (select * from gcm_users order by id desc) as X group by user_id) as g on p.user_id = g.user_id where p.type ='pending'"
15691 manish.sha 38
ALL_STORES_SQL = "select * from stores"
39
 
40
cursor.execute(ALL_STORES_SQL)
41
result_stores = cursor.fetchall()
42
domainStoresMap = {}
43
for rec in result_stores:
44
    domainStoresMap[rec[2]] = rec
15759 manish.sha 45
 
46
logging.basicConfig(level=logging.DEBUG,
47
                    format='[%(levelname)s] (%(threadName)-10s) %(message)s',
48
                    )
15691 manish.sha 49
 
50
 
51
class NotificationRecord():
52
    pushNotificationId = None
53
    userId = None
54
    campaignId = None
55
    campaignName = None
56
    title = None
57
    message= None
58
    type = None
59
    url = None
60
    expiresAt = None
61
    notificationStatus = None
62
    notificationCreated = None
63
    gcmRegId = None
64
 
65
    def __init__(self,pushNotificationId, userId, campaignId, campaignName, title, message, type, url, expiresAt, notificationStatus, notificationCreated, gcmRegId):
66
        self.pushNotificationId = pushNotificationId
67
        self.userId = userId
68
        self.campaignId = campaignId
69
        self.campaignName = campaignName
70
        self.title = title
71
        self.message= message
72
        self.type = type
73
        self.url = url
74
        self.expiresAt = expiresAt
75
        self.notificationStatus = notificationStatus
76
        self.notificationCreated = notificationCreated
77
        self.gcmRegId = gcmRegId
78
 
79
 
80
class NotificationThread (threading.Thread):
81
    def __init__(self, threadID, name, recordsList):
82
        threading.Thread.__init__(self)
83
        self.threadID = threadID
84
        self.name = name
85
        self.recordsList = recordsList
86
    def run(self):
15759 manish.sha 87
        logging.debug('Starting')
15691 manish.sha 88
        handleCampaignRequest(self.name, self.recordsList)
15759 manish.sha 89
        logging.debug('Completed')
15691 manish.sha 90
 
91
def handleCampaignRequest(threadName, recordsList ):
92
    for record in recordsList:
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])
94
        if notificationRecord.type=='url':
95
            parsed_uri = urlparse(notificationRecord.url)
96
            domain = '{uri.netloc}'.format(uri=parsed_uri)
15759 manish.sha 97
            logging.debug('Affiliate Domain:-'+str(domain))
98
            logging.debug('User Id:-'+str(notificationRecord.userId)+' And GCM Reg Id:- '+ str(notificationRecord.gcmRegId))
15691 manish.sha 99
            store = domainStoresMap.get(domain)
100
            if store is not None:
101
                url_params = { 'url' : notificationRecord.url,  'userId' : notificationRecord.userId, 'storeId' : store[0] }
102
                encoded_url_params = urllib.urlencode(url_params)
103
 
104
                DTR_API_BASIC_AUTH = base64.encodestring('%s:%s' % ("dtr", "dtr18Feb2015")).replace('\n', '')
105
 
106
                pushpostrequest = urllib2.Request('http://api.profittill.com/pushnotifications/generateAffiliateUrl', encoded_url_params, headers=aff_url_headers)
107
                pushpostrequest.add_header("Authorization", "Basic %s" % DTR_API_BASIC_AUTH)
108
                json_result =  json.loads(urllib2.urlopen(pushpostrequest).read())
109
                notificationRecord.url = json_result['url']
16294 manish.sha 110
                logging.debug('User Id:-'+str(notificationRecord.userId)+' Notification Url:- '+ str(notificationRecord.url))
15691 manish.sha 111
 
112
            data = {"message":notificationRecord.message,"cid":notificationRecord.campaignId,"title":notificationRecord.title,
113
                    "type":notificationRecord.type,"url":notificationRecord.url,"vibrate":1,"sound":1,"largeIcon":"large_icon",
114
                    "smallIcon":"small_icon"}
115
 
116
            post_data = {}
117
 
118
            post_data['data'] = data
15724 manish.sha 119
            regIds = []
120
            regIds.append(notificationRecord.gcmRegId)
121
            post_data['registration_ids'] = regIds
15691 manish.sha 122
 
123
            post_data_json = json.dumps(post_data)
16294 manish.sha 124
            logging.debug('User Id:- '+str(notificationRecord.userId)+' Post Data Json :- '+str(post_data_json))
15691 manish.sha 125
 
126
            response = requests.post(GCM_URL, data=post_data_json, headers=headers)
16294 manish.sha 127
            logging.debug('User Id:- '+str(notificationRecord.userId)+' Response :-'+str(response.text))
15725 manish.sha 128
            result = json.loads(response.text)
15691 manish.sha 129
            pushnotification = Pushnotifications.get_by(id=notificationRecord.pushNotificationId)
130
 
131
            if result["success"]:
132
                pushnotification.type = "sent"
133
                pushnotification.status = True
134
                pushnotification.message = "success"
135
                session.commit()
136
            else:
137
                pushnotification.type = "sent"
138
                pushnotification.status = False
139
                pushnotification.message = result["results"][0]["error"]
140
 
141
                updateGcmUserSql = "update gcm_users set failurecount=failurecount+1 where gcm_regid='%s'"%(notificationRecord.gcmRegId)
15759 manish.sha 142
                logging.debug('Update GCM User Query :-'+str(updateGcmUserSql))
15691 manish.sha 143
                try:
15726 manish.sha 144
                    dtrdb = MySQLdb.connect('localhost',"root","shop2020","dtr" )
145
                    cursor = dtrdb.cursor()
15691 manish.sha 146
                    cursor.execute(updateGcmUserSql)
15726 manish.sha 147
                    dtrdb.commit()
15691 manish.sha 148
                    session.commit()
15726 manish.sha 149
                    dtrdb.close()
15691 manish.sha 150
                except:
15726 manish.sha 151
                    dtrdb.rollback()
152
                    dtrdb.close()
15759 manish.sha 153
            #time.sleep(2)
15691 manish.sha 154
 
155
def chunks(l, n):
156
    """Yield successive n-sized chunks from l."""
157
    for i in xrange(0, len(l), n):
158
        yield l[i:i+n]
159
 
160
def main():
161
    parser = optparse.OptionParser()
162
    parser.add_option("-C", "--chunksize", dest="chunksize",
163
                      default="100",
164
                      type="int", help="The requsets a single thread handles",
165
                      metavar="CHUNKSIZE")
166
    (options, args) = parser.parse_args()
167
 
168
    cursor.execute(PUSH_NOTIFICATIONS_SQL)
169
    result_data = cursor.fetchall()
170
 
171
    count = 1
172
    DataService.initialize(db_hostname="localhost") 
173
    if result_data:
174
        campaign_receivers_list = list(chunks(result_data, options.chunksize))
175
        print len(campaign_receivers_list)
176
        for sublist in campaign_receivers_list:
177
            thread = NotificationThread(count, "Thread-"+str(count), sublist)
178
            thread.start()
179
            count = count +1
180
 
181
    db.close()
182
    if session.is_active:
183
        print "session is active. closing it."
184
        session.close()    
185
 
186
if __name__=='__main__':
187
    main()
188