def main(): values = Configuration.values() print values dbconn = SQLUtils( host=values['mysql-db']['sms_api_config']['host'], port=values['mysql-db']['sms_api_config']['port'], database=values['mysql-db']['sms_api_config']['db'], user=values['mysql-db']['sms_api_config']['user'], password=values['mysql-db']['sms_api_config']['password']) result = dbconn.run_query(query_type="select", query=query, fetchall=True) q = [] for r in result: client_id = create_sha256_signature(r['suffix'], r['email']) secret_key = create_client_id(r['email']) print client_id, secret_key, r['email'] print update_query % (client_id, secret_key, r['id']) q.append(update_query % (client_id, secret_key, r['id'])) dbconn.run_query("update", update_query, None, None) '-------------------------' for i in q: print i + ';'
class BaseSuffixUpdater(object): dbconn = None redisconn = None query_del_from_claimed_suffix = """delete from claimed_suffixes where account_id='%s'""" query_del_from_accounts = """update accounts set suffix=NULL, package='INACTIVE' where id='%s'""" key_cached_suffix = 'SMSAPI_%s' key_cached_suffix_credits = 'SMSAPI_%s_CREDITS' key_zero_credit_date = 'ZERO_CREDIT_DATE' def init(self): ''' @description: intializes: - configurations - db connections ''' Configuration.initialize() values = Configuration.values() self.dbconn = SQLUtils( host=values['mysql-db']['sms_api_config']['host'], port=values['mysql-db']['sms_api_config']['port'], database=values['mysql-db']['sms_api_config']['db'], user=values['mysql-db']['sms_api_config']['user'], password=values['mysql-db']['sms_api_config']['password']) self.redisconn = gredis.client.Connection( address=str(values['redis_servers']['sms_api']['host']), port=int(values['redis_servers']['sms_api']['port'])) self.redisconn.connect() print '-------' print 'redis:' print 'port: %s' % values['redis_servers']['sms_api']['port'] print 'host: %s' % values['redis_servers']['sms_api']['host'] print '\n' print 'sql:' print 'port: %s' % values['mysql-db']['sms_api_config']['host'] print 'host: %s' % values['mysql-db']['sms_api_config']['port'] print 'db: %s' % values['mysql-db']['sms_api_config']['db'] print 'user: %s' % values['mysql-db']['sms_api_config']['user'] print 'password: %s' % values['mysql-db']['sms_api_config']['password'] print '-------' def select_suffix(self, package='FREE', suffix='', extra_query=None, days='30'): ''' @description: - returns a list of ids and suffixes based from the params passed ''' if not extra_query: query = """select a.id, a.suffix, b.date_created from accounts as a, claimed_suffixes as b where a.status = 'ACTIVE' and a.package = '%s' and a.suffix = b.suffix and a.id = b.account_id and b.date_created + INTERVAL '%s' DAY < now()""" % (package, str(days)) else: query = """select a.id, a.suffix, b.date_created from accounts as a, claimed_suffixes as b where a.status = 'ACTIVE' and a.package = '%s' and a.suffix = b.suffix and a.id = b.account_id and %s""" % ( package, extra_query) print '\n - select suffix QUERY: - \n' print ' '.join(query.split()) try: return self.dbconn.run_query(query_type='select', query=query, fetchall=True) except Exception, e: print e return None
class ExpiredCheckoutDeleter(object): dbconn = None def main(self): ''' @description: - encapsulates the whole checkout deletion (for expired) of process ''' self.init() deleted_count = self.delete_expired_checkouts() print 'deleted %s checkout rows' % deleted_count def init(self): ''' @description: intializes: - configurations - db connections ''' Configuration.initialize() values = Configuration.values() self.dbconn = SQLUtils( host=values['mysql-db']['sms_api_config']['host'], port=values['mysql-db']['sms_api_config']['port'], database=values['mysql-db']['sms_api_config']['db'], user=values['mysql-db']['sms_api_config']['user'], password=values['mysql-db']['sms_api_config']['password']) def delete_expired_checkouts(self): ''' @description: - deletes the expired checkouts after 1 week of expiration ''' # --- logging purpose only --- ec_deleter_logger = sms_api_logger.StandAloneExpiredCheckoutDeleterLogger( ) query = """select * from checkout where expired='1' and (date_expiry + interval 7 day) <= now();""" expired_checkouts = self.dbconn.run_query(query_type='select', query=query) ec_deleter_logger.info('expired checkouts to be deleted', {'checkouts': str(expired_checkouts)}) # --- start deletion --- query = """delete from checkout where expired='1' and (date_expiry + interval 7 day) <= now();""" print '\n - delete expired checkout query - \n' print ' '.join(query.split()) try: return self.dbconn.run_query(query_type='delete', query=query) except Exception, e: print e return None
class CheckoutUpdater(object): dbconn = None def main(self): ''' @description: - encapsulates the whole checkout updating process ''' self.init() # co_ids = self.get_expired_checkouts() updated_count = self.update_checkout_expired_field() print 'Updated %s checkout rows' % updated_count def init(self): ''' @description: intializes: - configurations - db connections ''' Configuration.initialize() values = Configuration.values() self.dbconn = SQLUtils( host=values['mysql-db']['sms_api_config']['host'], port=values['mysql-db']['sms_api_config']['port'], database=values['mysql-db']['sms_api_config']['db'], user=values['mysql-db']['sms_api_config']['user'], password=values['mysql-db']['sms_api_config']['password']) def update_checkout_expired_field(self, expired='1'): ''' @description: - updates the column expired in checkout table @param expired (0 | 1): - 0 for not expired - 1 for expired @param checkout_ids(list of dicts) - i.e. [{'id': 1}, {'id': 10}, {'id': 9}] ''' # query = """update checkout set expired=%s where status = 'PENDING' # and expired=0 and (date_created + INTERVAL 30 MINUTE ) < now();""" % ( # expired) # checkout_logger = sms_api_logger.StandAloneCheckoutUpdaterLogger() query = """update checkout set expired=%s, date_updated=now() where (status IS NULL or status = 'PENDING') and expired=0 and date_expiry < now();""" % (expired) # checkout_logger.info('updating checkout table', # {'account_id': account_id, 'mobile': testmin}) print '\n - update expired field in checkout table - \n' print ' '.join(query.split()) try: return self.dbconn.run_query(query_type='update', query=query) except Exception, e: print e return None
class StatusUpdater(object): dbconn = None # --- queries that will be used in this feature --- query_sel_dragonpay_pending_status = """SELECT id FROM checkout WHERE mode_of_payment='DRAGONPAY' and (status='PENDING') ORDER BY id ASC""" query_update_dragonpay_status = """UPDATE dragonpay SET status='%s' WHERE txn_id='%s'""" def __init__(self): ''' @description: - initializes DB connections and other configurations ''' self.pool = Pool(1000) # used for spawning threads values = Configuration.values() # -- initializes DB -- self.dbconn = SQLUtils( host=values['mysql-db']['sms_api_config']['host'], port=values['mysql-db']['sms_api_config']['port'], database=values['mysql-db']['sms_api_config']['db'], user=values['mysql-db']['sms_api_config']['user'], password=values['mysql-db']['sms_api_config']['password']) print '-------' print 'DB:' print 'port: %s' % values['mysql-db']['sms_api_config']['host'] print 'host: %s' % values['mysql-db']['sms_api_config']['port'] print 'db: %s' % values['mysql-db']['sms_api_config']['db'] print 'user: %s' % values['mysql-db']['sms_api_config']['user'] print 'password: %s' % values['mysql-db']['sms_api_config']['password'] print '-------' # -- initializes dragonpay related config -- self.api_url = values['dragonpay']['api_url'] self.merchant_id = values['dragonpay']['merchant_id'] self.secret_key = values['dragonpay']['secret_key'] self.host = values['dragonpay']['host'] self.api_get_txn_status_url = values['dragonpay'][ 'api_get_txn_status_url'] self.uri = values['dragonpay']['uri'] parse_command_line() if options.config == 'prod': url = URL('https://%s' % values['dragonpay']['host']) else: url = URL('http://%s' % values['dragonpay']['host']) self.http_conn = HTTPClient.from_url(url, concurrency=10) def main(self): ''' @description: - encapsulates the whole dragonpay transaction status update process ''' payment_logger = sms_api_logger.PaymentLogger() pending_list = self.select_pending_status() if pending_list: for p in pending_list: # status = self.pool.spawn(self.get_txn_status, checkout_id=p) txn_id = DRAGONPAY_TXN_PREFIX % p['id'] lock_key = 'lock:%s' % str(txn_id) try: timeout = gevent.Timeout(TIMEOUT) timeout.start() if LockCache.lock(key=lock_key): # locks txn to avoid multiple processes return else: status = self.get_txn_status(txn_id) if status and status[0] == 'S': # success, payment_logger.info('dragonpay success', { 'txn_id': txn_id, 'status': status[0] }) on_payment_success_dragonpay(txn_id=txn_id, good_response=True) elif status[0] in ['F', 'V']: # failure, unknown, void payment_logger.info('dragonpay failed', { 'txn_id': txn_id, 'status': status[0] }) on_payment_success_dragonpay(txn_id=txn_id, good_response=False) else: # do nothing as of now # refund, chargeback, authorized pass # -- updates dragonpay status -- self.update_dragonpay_status(txn_id=txn_id, status=status[0]) LockCache.unlock(key=lock_key) except Exception: LockCache.unlock(key=lock_key) finally: timeout.cancel() def select_pending_status(self): ''' @description: - selects checkout ids from DB where status = 'PENDING' and mode of payment = 'DRAGONPAY' ''' try: return self.dbconn.run_query( query_type='select', query=self.query_sel_dragonpay_pending_status, fetchall=True) except Exception: import traceback print traceback.format_exc() def get_txn_status(self, txn_id): ''' @description: - performs soap call to dragonpay to know status of transaction ''' print txn_id body = """<?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Body> <GetTxnStatus xmlns="%s"> <merchantId>%s</merchantId> <password>%s</password> <txnId>%s</txnId> </GetTxnStatus> </soap:Body> </soap:Envelope>""" % (self.api_url, self.merchant_id, self.secret_key, txn_id) # print body headers = { 'Host': self.host, 'Content-Type': 'text/xml; charset=utf-8', 'Content-Length': "%d" % len(body), 'SOAPAction': self.api_get_txn_status_url } # print headers try: response = self.__parse_soap_response( self.http_conn.post(self.uri, body=body, headers=headers).read()) except Exception, e: import traceback print traceback.format_exc() return None # return response.read() print response return response
class BaseEmailNotifier(object): dbconn = None redisconn = None query_del_from_claimed_suffix = """delete from claimed_suffixes where account_id='%s'""" query_del_from_accounts = """update accounts set suffix=NULL where id='%s'""" key_cached_suffix = 'SMSAPI_%s' key_cached_suffix_credits = 'SMSAPI_%s_CREDITS' key_zero_credit_date = 'ZERO_CREDIT_DATE' def init(self): ''' @description: intializes: - configurations - db connections ''' Configuration.initialize() values = Configuration.values() self.dbconn = SQLUtils( host=values['mysql-db']['sms_api_config']['host'], port=values['mysql-db']['sms_api_config']['port'], database=values['mysql-db']['sms_api_config']['db'], user=values['mysql-db']['sms_api_config']['user'], password=values['mysql-db']['sms_api_config']['password']) self.redisconn = gredis.client.Connection( address=str(values['redis_servers']['sms_api']['host']), port=int(values['redis_servers']['sms_api']['port'])) self.redisconn.connect() self.mailer_settings = { 'host': values['mailer']['host'], 'port': values['mailer']['port'], 'from_address': values['mailer']['mail_from_address'] } print '-------' print 'sql:' print 'port: %s' % values['mysql-db']['sms_api_config']['host'] print 'host: %s' % values['mysql-db']['sms_api_config']['port'] print 'db: %s' % values['mysql-db']['sms_api_config']['db'] print 'user: %s' % values['mysql-db']['sms_api_config']['user'] print 'password: %s' % values['mysql-db']['sms_api_config']['password'] print '-------' def select_suffix(self, days_interval, status='ACTIVE', package='FREE', suffix=''): ''' @description: - returns a list of ids and suffixes based from the params passed ''' # query = """select a.id, a.suffix, b.date_created from accounts as a, # claimed_suffixes as b where a.status = '%s' and a.package = '%s' # and a.suffix = b.suffix and a.id = b.account_id # and b.date_created= (b.date_created + INTERVAL %s DAY)""" %( # status, package, days_interval) query = """select a.id, a.suffix, a.email, b.date_created from accounts as a, claimed_suffixes as b where a.status = '%s' and a.package = '%s' and a.suffix = b.suffix and a.id = b.account_id and month(now()) = month(b.date_created + INTERVAL %s DAY) and day(now()) = day(b.date_created + INTERVAL %s DAY) and year(now()) = year(b.date_created + INTERVAL %s DAY)""" % ( status, package, days_interval, days_interval, days_interval) print '\n - select suffix QUERY: - \n' print ' '.join(query.split()) try: return self.dbconn.run_query(query_type='select', query=query, fetchall=True) except Exception, e: print e return None