Subversion Repositories SmartDukaan

Rev

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