Subversion Repositories SmartDukaan

Rev

Rev 16426 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

import time
import datetime

import MySQLdb
from dtr.storage import DataService
from dtr.storage.DataService import Pushnotifications
from elixir import *
from sqlalchemy.orm.exc import NoResultFound, MultipleResultsFound
from sqlalchemy.sql import func
from sqlalchemy.sql.expression import and_, or_, desc, not_, distinct, cast, \
    between
from urlparse import urlparse
import requests
import json
import optparse
import urllib2
import base64
import urllib
import logging


class NotificationRecord():
    pushNotificationId = None
    userId = None
    campaignId = None
    campaignName = None
    title = None
    message= None
    type = None
    url = None
    expiresAt = None
    notificationStatus = None
    notificationCreated = None
    gcmRegId = None
    
    def __init__(self,pushNotificationId, userId, campaignId, campaignName, title, message, type, url, expiresAt, notificationStatus, notificationCreated, gcmRegId):
        self.pushNotificationId = pushNotificationId
        self.userId = userId
        self.campaignId = campaignId
        self.campaignName = campaignName
        self.title = title
        self.message= message
        self.type = type
        self.url = url
        self.expiresAt = expiresAt
        self.notificationStatus = notificationStatus
        self.notificationCreated = notificationCreated
        self.gcmRegId = gcmRegId

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"
GCM_URL = "https://android.googleapis.com/gcm/send"
GOOGLE_API_KEY = "AIzaSyDw1qBnmxtnfR9NqBewryQ-yo3cG2ravGM"
headers = {'content-type':'application/json', "authorization":"key=" + GOOGLE_API_KEY}
aff_url_headers = { 
            'User-agent':'Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36',
            'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',      
            'Accept-Language' : 'en-US,en;q=0.8',                     
            'Accept-Charset' : 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
            'Connection':'keep-alive'
        }

db = MySQLdb.connect('localhost',"root","shop2020","dtr" )
cursor = db.cursor()
DataService.initialize(db_hostname="localhost")

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"
ALL_STORES_SQL = "select * from stores"
logging.basicConfig(level=logging.DEBUG,
                    format='[%(levelname)s] %(message)s',
                    )

cursor.execute(PUSH_NOTIFICATIONS_RETRY_SQL)
retry_records_data = cursor.fetchall()
if retry_records_data:
    cursor.execute(ALL_STORES_SQL)
    result_stores = cursor.fetchall()
    domainStoresMap = {}
    for rec in result_stores:
        domainStoresMap[rec[2]] = rec
    for record in retry_records_data:
        pushNotificationFinalSql = PUSH_NOTIFICATIONS_SQL%(record[1])
        print pushNotificationFinalSql
        cursor.execute(pushNotificationFinalSql)
        notificationRecordData = cursor.fetchone()
        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])
        if notificationRecord.type=='url':
            parsed_uri = urlparse(notificationRecord.url)
            domain = '{uri.netloc}'.format(uri=parsed_uri)
            logging.debug('Affiliate Domain:-'+str(domain))
            logging.debug('User Id:-'+str(notificationRecord.userId)+' And GCM Reg Id:- '+ str(notificationRecord.gcmRegId))
            store = domainStoresMap.get(domain)
            if store is not None:
                url_params = { 'url' : notificationRecord.url,  'userId' : notificationRecord.userId, 'storeId' : store[0] }
                encoded_url_params = urllib.urlencode(url_params)
                
                DTR_API_BASIC_AUTH = base64.encodestring('%s:%s' % ("dtr", "dtr18Feb2015")).replace('\n', '')
                
                pushpostrequest = urllib2.Request('http://api.profittill.com/pushnotifications/generateAffiliateUrl', encoded_url_params, headers=aff_url_headers)
                pushpostrequest.add_header("Authorization", "Basic %s" % DTR_API_BASIC_AUTH)
                json_result =  json.loads(urllib2.urlopen(pushpostrequest).read())
                notificationRecord.url = json_result['url']
                logging.debug('User Id:-'+str(notificationRecord.userId)+' Notification Url:- '+ str(notificationRecord.url))
            else:
                notificationRecord.url = notificationRecord.url+'?user_id='+str(notificationRecord.userId)
                logging.debug('User Id:-'+str(notificationRecord.userId)+' Notification Url:- '+ str(notificationRecord.url))
            data = {"message":notificationRecord.message,"cid":notificationRecord.campaignId,"title":notificationRecord.title,
                    "type":notificationRecord.type,"url":notificationRecord.url,"vibrate":1,"sound":1,"largeIcon":"large_icon",
                    "smallIcon":"small_icon","priority":"high","time_to_live":long(time.mktime(notificationRecord.expiresAt.timetuple()))-long(time.mktime(datetime.datetime.now().timetuple()))}
            
            post_data = {}
 
            post_data['data'] = data
            regIds = []
            regIds.append(notificationRecord.gcmRegId)
            post_data['registration_ids'] = regIds
             
            post_data_json = json.dumps(post_data)
            logging.debug('User Id:- '+str(notificationRecord.userId)+' Post Data Json :- '+str(post_data_json))
            
            response = requests.post(GCM_URL, data=post_data_json, headers=headers)
            logging.debug('User Id:- '+str(notificationRecord.userId)+' Response :-'+str(response.text))
            result = json.loads(response.text)
            pushnotification = Pushnotifications.get_by(id=notificationRecord.pushNotificationId)
            
            if result["success"]:
                if pushnotification.message is None or pushnotification.message!="success":
                    pushnotification.type = "sent"
                    pushnotification.status = True
                    pushnotification.message = "success"
                    session.commit()
            else:
                pushnotification.type = "sent"
                pushnotification.status = False
                pushnotification.message = result["results"][0]["error"]
                
                updateGcmUserSql = "update gcm_users set failurecount=failurecount+1 where gcm_regid='%s'"%(notificationRecord.gcmRegId)
                logging.debug('Update GCM User Query :-'+str(updateGcmUserSql))
                try:
                    dtrdb = MySQLdb.connect('localhost',"root","shop2020","dtr" )
                    cursor = dtrdb.cursor()
                    cursor.execute(updateGcmUserSql)
                    dtrdb.commit()
                    session.commit()
                    dtrdb.close()
                except:
                    dtrdb.rollback()
                    dtrdb.close()
        

db.close()
if session.is_active:
    print "session is active. closing it."
    session.close()