def getAgent(self, bc, prot, userid, passwd): ma = ManageAgent(bc.dbconn, bc.cacheconn) if ma.resolveProtocol(prot) != userid: return False x = ma.verifyAgent(userid, passwd) if x['code'] == agent.AGST_FOUND: return x['agent'] return False
def web_trx(self, agent_id, product, msisdn, pin): bc = AgentNotifier() ma = ManageAgent(bc.dbconn, bc.cacheconn) hlrmap = HLRMap(bc.dbconn, bc.cacheconn) x = ma.verifyAgent(agent_id, '1234', True, False) if x['code'] in (agent.AGST_NOTFOUND, agent.AGST_NOTACTIVE): return json.dumps({'success': 0, 'reason': 'Agent not registered / not active'}) prod_c = DBCache(const.PRODUCT_PREFIX, config.DEFAULT_EXPIRE, const.PRODUCT_SQL) prod = prod_c.get(bc.dbconn, bc.cacheconn, product) if not prod: return json.dumps({'success': 0, 'reason': 'Invalid product id'}) msisdn = sanitizeMSISDN(msisdn) method = firstMethod(hlrmap, prod, msisdn) tran_id = self.topup(bc, x['agent'], msisdn, prod, method) return json.dumps({'success': 1, 'reason': '', 'tranid': tran_id})
def __init__(self): super(TopupParser, self).__init__('UNKN', 'INVL', 'TopupParser') self.agent_manager = ManageAgent(self.dbconn, self.cacheconn) self.dm = DepositMutation(5, self.dbconn, self.cacheconn) self.um = UnitMutation(5, self.dbconn, self.cacheconn) self.hlrmap = HLRMap(self.dbconn, self.cacheconn) cdf = config.DEFAULT_EXPIRE self.c_product = DBCache(const.PRODUCT_PREFIX, cdf, const.PRODUCT_SQL) self.c_price = DBCache(const.AGENTPRICE_PREFIX, cdf, const.AGENTPRICE_SQL) self.c_operator = DBCache(const.OPERATOR_PREFIX, cdf, const.OPERATOR_SQL, user_func={'prefix': lambda x: x.split(',')}) map(lambda x: x.setConn(self.dbconn, self.cacheconn), [ self.c_product, self.c_price, self.c_operator, ]) self.rx_check, self.rx_topup, self.rx_separator = (None, None, None) self._init2() self.log = mylogger('TopupParser', 'topupparser.log') self.to_db = [] self.parsed = [] self.handler = [ self.check, ] self.processUNKN = self.process
def bnisms(self): if cherrypy.request.remote.ip not in self.auth_ip: print 'UNAUTH IP {0}'.format(cherrypy.request.remote.ip) return bc = BaseComponent() ma = ManageAgent(bc.dbconn, bc.cacheconn) try: # if 'xml' not in cherrypy.request.headers['content-type']: # return 'Content is not XML' x = cherrypy.request.body.read() print x dom1 = parseString(x) except: return 'Unable to parse XML document' cherrypy.response.headers['content-type'] = 'text/xml; charset=\"UTF-8\"' berita = self.getText(dom1, 'berita') trxid = self.getText(dom1, 'trxid') try: amount = int(self.getText(dom1, 'amount')) except: amount = 0 product = self.getText(dom1, 'product') msisdn = self.getText(dom1, 'msisdn') status = '999' top_element = 'response_trx' message = berita ag = None product = product.upper() if product in self.prod_list: status = '00' amount = self.prod_list[product] elif product not in self.prod_list and product != 'ALL': status = '08' elif berita.upper() == 'CEKMSISDN': top_element = 'response_alert' ag = ma.resolveProtocol('sms://{0}'.format(msisdn)) if not ag: status = '07' else: status = '00' message = msisdn else: ag = ma.resolveProtocol('sms://{0}'.format(msisdn)) if not ag: status = '07' elif amount == 0: status = '05' else: r = self._callAdminHelper('depmut_execute', { 'agent_id': ag, 'type': 'C', 'amount': int(amount), 'comment': 'BNI SMS', }) if r['success'] == 1: status = '00' else: status = '05' sql = '''INSERT INTO `agent_deposit` (`mutation_id`,`timestamp`, `agent_id`,`mutation`,`type`,`deposit_balance`,`source`, `comment`) VALUES (%s,%s,%s,%s,%s,%s,%s,%s)''' c = bc.dbconn.cursor(MySQLdb.cursors.DictCursor) c.execute(sql, (r['mutation_id'], datetime.now(), ag, int(amount), 'C', r['balance'], 'BNI-NARINDO','SMS')) bc.dbconn.commit() c.close() doc = self.createXML({ 'trxid': trxid, 'receiptcode': datetime.today().strftime('%H%M%S'), 'msisdn': msisdn, 'amount': amount, 'product': product, 'msg': message, 'status': status, }, top_element) result = doc.toxml() print result bc.dbconn.close(); return result
def __init__(self, name='XX'): super(AgentNotifier, self).__init__(name) self.am = ManageAgent(self.dbconn, self.cacheconn)
class AgentNotifier(BaseComponent): '''Class focusing on notifying agent''' def __init__(self, name='XX'): super(AgentNotifier, self).__init__(name) self.am = ManageAgent(self.dbconn, self.cacheconn) def productIdAndOrder(self, prod_id, order): '''Returns product_id.order only if order > 1''' if int(order) > 1: return '{0}.{1}'.format(prod_id, order) else: return prod_id def buildSubTopupSucess(self, param): '''Build substitution dictionary for a "transaction_successful" message. Needed parameters: - agent_id - reg_protocol - product_id - order - msisdn_destination - references - deposit - sell_price ''' if not isinstance(param, dict): return False to_sub = {} to_sub['product_id'] = self.productIdAndOrder(param['product_id'], param['order']) to_sub['dest'] = param['msisdn_destination'] to_sub['ref'] = param['references'] to_sub['balance'] = thousandSeparator(param['deposit']) to_sub['price'] = thousandSeparator(param.get('sell_price', 0)) to_sub['agent_id'] = param.get('agent_id', '') to_sub['name'] = self.am.getAgentData(param['agent_id'])['agent_name'] to_sub['unit'] = param['product_id'] return to_sub def notifyTopupSucess(self, param): '''Send a "transaction_successful" to an agent. Needed parameters: - agent_id - reg_protocol - product_id - order - msisdn_destination - references - deposit - sell_price - type ''' t = param.get('type', 1) if t == 3: msg = 'transaction_successful_unit' else: msg = 'transaction_successful' self.writeNotifyOut(param['reg_protocol'], msg, self.buildSubTopupSucess(param)) def buildSubTopupFail(self, param, precompute): '''Build substitution dictionary for a "transaction_fail" message. Needed parameters: - reg_protocol - product_id - order - msisdn_destination - deposit - sell_price - type ''' if not isinstance(param, dict): return False to_sub = {} to_sub['product_id'] = self.productIdAndOrder(param['product_id'], param['order']) to_sub['dest'] = param['msisdn_destination'] to_sub['unit'] = param['product_id'] if precompute: to_sub['balance'] = thousandSeparator(param['deposit']) else: t = param.get('type', 1) if t == 3: to_sub['balance'] = int(param['deposit']) + 1 else: to_sub['balance'] = int(param['deposit']) + int(param['sell_price']) return to_sub def notifyTopupFail(self, param, precompute=True): '''Send a "transaction_fail" to an agent. Needed parameters: - reg_protocol - product_id - order - msisdn_destination - deposit - sell_price - type ''' t = param.get('type', 1) if t == 3: msg = 'transaction_fail_unit' else: msg = 'transaction_fail' self.writeNotifyOut(param['reg_protocol'], msg, self.buildSubTopupFail(param, precompute))
class TopupParser(ProcessNotifyIn): def __init__(self): super(TopupParser, self).__init__('UNKN', 'INVL', 'TopupParser') self.agent_manager = ManageAgent(self.dbconn, self.cacheconn) self.dm = DepositMutation(5, self.dbconn, self.cacheconn) self.um = UnitMutation(5, self.dbconn, self.cacheconn) self.hlrmap = HLRMap(self.dbconn, self.cacheconn) cdf = config.DEFAULT_EXPIRE self.c_product = DBCache(const.PRODUCT_PREFIX, cdf, const.PRODUCT_SQL) self.c_price = DBCache(const.AGENTPRICE_PREFIX, cdf, const.AGENTPRICE_SQL) self.c_operator = DBCache(const.OPERATOR_PREFIX, cdf, const.OPERATOR_SQL, user_func={'prefix': lambda x: x.split(',')}) map(lambda x: x.setConn(self.dbconn, self.cacheconn), [ self.c_product, self.c_price, self.c_operator, ]) self.rx_check, self.rx_topup, self.rx_separator = (None, None, None) self._init2() self.log = mylogger('TopupParser', 'topupparser.log') self.to_db = [] self.parsed = [] self.handler = [ self.check, ] self.processUNKN = self.process def _init2(self): c = self.dbconn.cursor(MySQLdb.cursors.DictCursor) c.execute('SELECT `regex`,`separator` from `parse` where `name`=' \ '"topup" LIMIT 1') tmp = c.fetchone() self.rx_topup, self.rx_separator = tmp['regex'], tmp['separator'] c.execute('SELECT `regex` from `parse` where `name`=' \ '"initial_check" LIMIT 1') tmp = c.fetchone() self.rx_check = tmp['regex'] c.close() def check(self, r, tmp): def timeDifference(t): tmp = datetime.now() - datetime.strptime(t, '%y/%m/%d %H:%M:%S') if tmp.days >= 0: return tmp.seconds else: return -tmp.seconds parse_obj = re.match(self.rx_check, r['parameters'], re.IGNORECASE) if not parse_obj: return True parse_result = parse_obj.groupdict() if timeDifference(parse_result['time_sent']) > \ config.REQUEST_VALID_PERIOD: raise Timeout(self, r, tmp) prot = parse_result['protocol'] agent_id = self.agent_manager.resolveProtocol(prot) if not agent_id: self.writeNotifyOut(prot, 'agent_invalid') print 'AGST_NOTFOUND {0}'.format(prot) return True ag = self.agent_manager.verifyAgent(agent_id, 'xxxx') if ag['code'] == AGST_NOTFOUND or ag['code'] == AGST_NOTACTIVE: self.writeNotifyOut(prot, 'agent_invalid') print 'Reject non-active agent {0}'.format(agent_id) return True x = self.cmdList() _, _, _, _, msg = r['parameters'].split(',', 4) for c in x: cmd, _, _ = msg.partition(x[c]) if cmd.upper() == c: raise UNMS(self, r, tmp) parse_obj = re.match(self.rx_topup, r['parameters'], re.IGNORECASE) if not parse_obj: raise UNMS(self, r, tmp) parse_result = parse_obj.groupdict() try: self._topup(r['id'], agent_id, parse_result) except Error, e: if e.msg == AGST_NOTFOUND: self.writeNotifyOut(prot, 'agent_invalid') elif e.msg == AGST_NOTACTIVE: self.writeNotifyOut(prot, 'agent_invalid') elif e.msg == AGST_WRONGPIN: self.writeNotifyOut(prot, 'wrong_pin') elif e.msg == WRONG_REQ_FORMAT: self.writeNotifyOut(prot, 'wrong_req_format') finally: