Subversion Repositories SmartDukaan

Rev

Rev 16425 | Go to most recent revision | Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
16413 manish.sha 1
import time
2
import datetime
3
 
4
import MySQLdb
5
from dtr.storage import DataService
6
from dtr.storage.DataService import Pushnotifications
7
from elixir import *
8
from sqlalchemy.orm.exc import NoResultFound, MultipleResultsFound
9
from sqlalchemy.sql import func
10
from sqlalchemy.sql.expression import and_, or_, desc, not_, distinct, cast, \
11
    between
12
from urlparse import urlparse
13
import requests
14
import json
15
import optparse
16
import urllib2
17
import base64
18
import urllib
19
import logging
20
 
21
 
22
class NotificationRecord():
23
    pushNotificationId = None
24
    userId = None
25
    campaignId = None
26
    campaignName = None
27
    title = None
28
    message= None
29
    type = None
30
    url = None
31
    expiresAt = None
32
    notificationStatus = None
33
    notificationCreated = None
34
    gcmRegId = None
35
 
36
    def __init__(self,pushNotificationId, userId, campaignId, campaignName, title, message, type, url, expiresAt, notificationStatus, notificationCreated, gcmRegId):
37
        self.pushNotificationId = pushNotificationId
38
        self.userId = userId
39
        self.campaignId = campaignId
40
        self.campaignName = campaignName
41
        self.title = title
42
        self.message= message
43
        self.type = type
44
        self.url = url
45
        self.expiresAt = expiresAt
46
        self.notificationStatus = notificationStatus
47
        self.notificationCreated = notificationCreated
48
        self.gcmRegId = gcmRegId
49
 
50
PUSH_NOTIFICATIONS_RETRY_SQL ="select  x.user_id, x.id, x.created, x.notification_campaign_id, x.sent-IF (y.received is null, 0, y.received) failureCount, x.last_active, x.expiresat from (select p.id,p.user_id, p.created, p.notification_campaign_id, count(*) sent, ua.last_active, n.expiresat from pushnotifications p join notification_campaigns n on p.notification_campaign_id = n.id join useractive ua on p.user_id = ua.user_id where p.notification_campaign_id in (select id from notification_campaigns where TIMESTAMPDIFF(HOUR, created, NOW())<=2) and p.type='sent' and p.message = 'success' and ua.last_active >= p.created and ua.last_active <= n.expiresat group by p.id) as x left join (select p.id, p.user_id, p.created, p.notification_campaign_id, count(*) received, ua.last_active, n.expiresat from pushnotifications p join notification_campaigns n on p.notification_campaign_id = n.id join useractive ua on p.user_id = ua.user_id where p.notification_campaign_id in (select id from notification_campaigns where TIMESTAMPDIFF(HOUR, created, NOW())<=2) and p.type='recieved' group by p.id) as y on (x.user_id = y.user_id and x.notification_campaign_id = y.notification_campaign_id) having failureCount =1"
51
GCM_URL = "https://android.googleapis.com/gcm/send"
52
GOOGLE_API_KEY = "AIzaSyDw1qBnmxtnfR9NqBewryQ-yo3cG2ravGM"
53
headers = {'content-type':'application/json', "authorization":"key=" + GOOGLE_API_KEY}
54
aff_url_headers = { 
55
            'User-agent':'Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36',
56
            'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',      
57
            'Accept-Language' : 'en-US,en;q=0.8',                     
58
            'Accept-Charset' : 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
59
            'Connection':'keep-alive'
60
        }
61
 
62
db = MySQLdb.connect('localhost',"root","shop2020","dtr" )
63
cursor = db.cursor()
64
DataService.initialize(db_hostname="localhost")
65
 
66
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.id =%d"
67
ALL_STORES_SQL = "select * from stores"
68
logging.basicConfig(level=logging.DEBUG,
69
                    format='[%(levelname)s] %(message)s',
70
                    )
71
 
72
cursor.execute(PUSH_NOTIFICATIONS_RETRY_SQL)
73
retry_records_data = cursor.fetchall()
74
if retry_records_data:
75
    cursor.execute(ALL_STORES_SQL)
76
    result_stores = cursor.fetchall()
77
    domainStoresMap = {}
78
    for rec in result_stores:
79
        domainStoresMap[rec[2]] = rec
80
    for record in retry_records_data:
81
        pushNotificationFinalSql = PUSH_NOTIFICATIONS_SQL%(record[1])
82
        print pushNotificationFinalSql
83
        cursor.execute(pushNotificationFinalSql)
84
        notificationRecordData = cursor.fetchone()
85
        notificationRecord = NotificationRecord(notificationRecordData[0], notificationRecordData[1], notificationRecordData[2], notificationRecordData[3], notificationRecordData[4], notificationRecordData[5], notificationRecordData[6], notificationRecordData[7], notificationRecordData[9], notificationRecordData[10], notificationRecordData[11], notificationRecordData[12])
86
        if notificationRecord.type=='url':
87
            parsed_uri = urlparse(notificationRecord.url)
88
            domain = '{uri.netloc}'.format(uri=parsed_uri)
89
            logging.debug('Affiliate Domain:-'+str(domain))
90
            logging.debug('User Id:-'+str(notificationRecord.userId)+' And GCM Reg Id:- '+ str(notificationRecord.gcmRegId))
91
            store = domainStoresMap.get(domain)
92
            if store is not None:
93
                url_params = { 'url' : notificationRecord.url,  'userId' : notificationRecord.userId, 'storeId' : store[0] }
94
                encoded_url_params = urllib.urlencode(url_params)
95
 
96
                DTR_API_BASIC_AUTH = base64.encodestring('%s:%s' % ("dtr", "dtr18Feb2015")).replace('\n', '')
97
 
98
                pushpostrequest = urllib2.Request('http://api.profittill.com/pushnotifications/generateAffiliateUrl', encoded_url_params, headers=aff_url_headers)
99
                pushpostrequest.add_header("Authorization", "Basic %s" % DTR_API_BASIC_AUTH)
100
                json_result =  json.loads(urllib2.urlopen(pushpostrequest).read())
101
                notificationRecord.url = json_result['url']
102
                logging.debug('User Id:-'+str(notificationRecord.userId)+' Notification Url:- '+ str(notificationRecord.url))
103
            else:
104
                notificationRecord.url = notificationRecord.url+'?user_id='+str(notificationRecord.userId)
105
                logging.debug('User Id:-'+str(notificationRecord.userId)+' Notification Url:- '+ str(notificationRecord.url))
106
            data = {"message":notificationRecord.message,"cid":notificationRecord.campaignId,"title":notificationRecord.title,
107
                    "type":notificationRecord.type,"url":notificationRecord.url,"vibrate":1,"sound":1,"largeIcon":"large_icon",
108
                    "smallIcon":"small_icon","priority":"high","time_to_live":long(time.mktime(notificationRecord.expiresAt.timetuple()))-long(time.mktime(datetime.datetime.now().timetuple()))}
109
 
110
            post_data = {}
111
 
112
            post_data['data'] = data
113
            regIds = []
114
            regIds.append(notificationRecord.gcmRegId)
115
            post_data['registration_ids'] = regIds
116
 
117
            post_data_json = json.dumps(post_data)
118
            logging.debug('User Id:- '+str(notificationRecord.userId)+' Post Data Json :- '+str(post_data_json))
119
 
120
            response = requests.post(GCM_URL, data=post_data_json, headers=headers)
121
            logging.debug('User Id:- '+str(notificationRecord.userId)+' Response :-'+str(response.text))
122
            result = json.loads(response.text)
123
            pushnotification = Pushnotifications.get_by(id=notificationRecord.pushNotificationId)
124
 
125
            if result["success"]:
126
                if pushnotification.message is None or pushnotification.message!="success":
127
                    pushnotification.type = "sent"
128
                    pushnotification.status = True
129
                    pushnotification.message = "success"
130
                    session.commit()
131
            else:
132
                pushnotification.type = "sent"
133
                pushnotification.status = False
134
                pushnotification.message = result["results"][0]["error"]
135
 
136
                updateGcmUserSql = "update gcm_users set failurecount=failurecount+1 where gcm_regid='%s'"%(notificationRecord.gcmRegId)
137
                logging.debug('Update GCM User Query :-'+str(updateGcmUserSql))
138
                try:
139
                    dtrdb = MySQLdb.connect('localhost',"root","shop2020","dtr" )
140
                    cursor = dtrdb.cursor()
141
                    cursor.execute(updateGcmUserSql)
142
                    dtrdb.commit()
143
                    session.commit()
144
                    dtrdb.close()
145
                except:
146
                    dtrdb.rollback()
147
                    dtrdb.close()
148
 
149
 
150
db.close()
151
if session.is_active:
152
    print "session is active. closing it."
153
    session.close()