Subversion Repositories SmartDukaan

Rev

Rev 16294 | Rev 16350 | 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))
16295 manish.sha 111
            else:
112
                notificationRecord.url = notificationRecord.url+'?user_id='+str(notificationRecord.userId)
15691 manish.sha 113
 
114
            data = {"message":notificationRecord.message,"cid":notificationRecord.campaignId,"title":notificationRecord.title,
115
                    "type":notificationRecord.type,"url":notificationRecord.url,"vibrate":1,"sound":1,"largeIcon":"large_icon",
116
                    "smallIcon":"small_icon"}
117
 
118
            post_data = {}
119
 
120
            post_data['data'] = data
15724 manish.sha 121
            regIds = []
122
            regIds.append(notificationRecord.gcmRegId)
123
            post_data['registration_ids'] = regIds
15691 manish.sha 124
 
125
            post_data_json = json.dumps(post_data)
16294 manish.sha 126
            logging.debug('User Id:- '+str(notificationRecord.userId)+' Post Data Json :- '+str(post_data_json))
15691 manish.sha 127
 
128
            response = requests.post(GCM_URL, data=post_data_json, headers=headers)
16294 manish.sha 129
            logging.debug('User Id:- '+str(notificationRecord.userId)+' Response :-'+str(response.text))
15725 manish.sha 130
            result = json.loads(response.text)
15691 manish.sha 131
            pushnotification = Pushnotifications.get_by(id=notificationRecord.pushNotificationId)
132
 
133
            if result["success"]:
134
                pushnotification.type = "sent"
135
                pushnotification.status = True
136
                pushnotification.message = "success"
137
                session.commit()
138
            else:
139
                pushnotification.type = "sent"
140
                pushnotification.status = False
141
                pushnotification.message = result["results"][0]["error"]
142
 
143
                updateGcmUserSql = "update gcm_users set failurecount=failurecount+1 where gcm_regid='%s'"%(notificationRecord.gcmRegId)
15759 manish.sha 144
                logging.debug('Update GCM User Query :-'+str(updateGcmUserSql))
15691 manish.sha 145
                try:
15726 manish.sha 146
                    dtrdb = MySQLdb.connect('localhost',"root","shop2020","dtr" )
147
                    cursor = dtrdb.cursor()
15691 manish.sha 148
                    cursor.execute(updateGcmUserSql)
15726 manish.sha 149
                    dtrdb.commit()
15691 manish.sha 150
                    session.commit()
15726 manish.sha 151
                    dtrdb.close()
15691 manish.sha 152
                except:
15726 manish.sha 153
                    dtrdb.rollback()
154
                    dtrdb.close()
15759 manish.sha 155
            #time.sleep(2)
15691 manish.sha 156
 
157
def chunks(l, n):
158
    """Yield successive n-sized chunks from l."""
159
    for i in xrange(0, len(l), n):
160
        yield l[i:i+n]
161
 
162
def main():
163
    parser = optparse.OptionParser()
164
    parser.add_option("-C", "--chunksize", dest="chunksize",
165
                      default="100",
166
                      type="int", help="The requsets a single thread handles",
167
                      metavar="CHUNKSIZE")
168
    (options, args) = parser.parse_args()
169
 
170
    cursor.execute(PUSH_NOTIFICATIONS_SQL)
171
    result_data = cursor.fetchall()
172
 
173
    count = 1
174
    DataService.initialize(db_hostname="localhost") 
175
    if result_data:
176
        campaign_receivers_list = list(chunks(result_data, options.chunksize))
177
        print len(campaign_receivers_list)
178
        for sublist in campaign_receivers_list:
179
            thread = NotificationThread(count, "Thread-"+str(count), sublist)
180
            thread.start()
181
            count = count +1
182
 
183
    db.close()
184
    if session.is_active:
185
        print "session is active. closing it."
186
        session.close()    
187
 
188
if __name__=='__main__':
189
    main()
190