Subversion Repositories SmartDukaan

Rev

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