Subversion Repositories SmartDukaan

Rev

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