示例#1
0
 def post(self):
     #user_id,device_id,fcm_token,update_token=True/False
     data = request.get_json()
     current_app.logger.info(
         "Scorepesa mobile app device register api args %r" % data)
     scorepesa_cfgs = LocalConfigParser.parse_configs("SCOREPESAAPP")
     scorepesa_bonus_cfgs = LocalConfigParser.parse_configs("SCOREPESA")
     try:
         http_code = 200
         current_app.logger.info("device registeration data..... %r" % data)
         helper = Helper(current_app.logger)
         result = helper.scorepesa_app_register_device(data)
         current_app.logger.info(
             "mobile device registration response... {0}".format(result))
         if not result:
             http_code = 500
             result = 'ERROR'
         if result and data.get("update_token") is False:
             #award bonus
             if (helper.award_bonus_to_profile(data)):
                 #sent app notification/sms
                 data[
                     'msg'] = "Congratulations! you have been awarded a bonus worth KES {0}. Now win big with.".format(
                         scorepesa_bonus_cfgs['registration_bunus_amount'])
                 data['sc'] = "101010"
                 helper.push_notification(data)
                 helper.send_message(data)
     except JWTError as e:
         current_app.logger.error(
             "Exception on device registration.... %r " % e)
         http_code = 400
         result = "Invalid request."
     resp = make_response(json.dumps(result), http_code)
     return resp
示例#2
0
    def __init__(self, logger, port=3306):

        self.db_configs = LocalConfigParser.parse_configs("DB")
        self.sdp_configs = LocalConfigParser.parse_configs("SDP")
        self.bulk_configs = LocalConfigParser.parse_configs("SDP_CONFIGS")
        self.host = self.db_configs['host']
        self.db = self.db_configs['db_name']
        self.username = self.db_configs['username']
        self.password = self.db_configs['password']
        self.port = self.db_configs['port'] or port

        self.db_uri = self.get_connection_uri()
        self.engine = self.get_engine()
        self.db_session = self.get_db_session()
        self.logger = logger
示例#3
0
 def post(self):
     #version_number
     data = request.get_json()
     current_app.logger.info(
         "Scorepesa mobile app change version api args %r" % data)
     scorepesa_cfgs = LocalConfigParser.parse_configs("SCOREPESAAPP")
     try:
         http_code = 200
         current_app.logger.info(
             "scorepesa app api change version data %r" % data)
         helper = Helper(current_app.logger)
         message = {"vnum": data.get('version_number')}
         result = helper.scorepesa_app_update_version(message)
         current_app.logger.info(
             "mobile change version response... {0}".format(result))
         if not result:
             http_code = 500
             result = 'ERROR'
     except JWTError as e:
         current_app.logger.error("Exception on version check ..... %r " %
                                  e)
         http_code = 400
         result = "Invalid request."
     resp = make_response(json.dumps(result), http_code)
     return resp
示例#4
0
    def get(self, ops='android'):
        #args = request.args
        current_app.logger.info("download request....{0}".format(ops))
        if not ops:
            return "Bad request", 400
        scorepesa_app_cfgs = LocalConfigParser.parse_configs("SCOREPESAAPP")
        directory = scorepesa_app_cfgs['scorepesa_app_directory']
        if ops == "android":  #args.get("os") == "android":
            android_apk_name = scorepesa_app_cfgs['android_app_name']
            file_ext = scorepesa_app_cfgs['android_app_extension']
        else:
            return make_response("Sorry request failed.", 200)
        filename = '{0}.{1}'.format(android_apk_name, file_ext)
        #check if requested file exists if not pull first
        current_app.logger.info("got download details....{0}:::{1}".format(
            directory, filename))

        fpath = "{0}/{1}".format(directory, filename)
        if not os.path.isfile(fpath):
            self.pull_apk_for_download_first()
        result = send_from_directory(directory, filename, as_attachment=True)
        '''
         TODO:

            record downloads count
        '''

        return result
示例#5
0
 def post(self):
     parser = reqparse.RequestParser()
     parser.add_argument('token',
                         type=str,
                         required=True,
                         help='Provide token')
     args = parser.parse_args(strict=True)
     scorepesa_cfgs = LocalConfigParser.parse_configs("SCOREPESA")
     current_app.logger.info(
         "JWT Virtuals bet api args :: {0} :configs: {1}".format(
             args, scorepesa_cfgs['encrption_key']))
     response = 'Bad Request'
     status = 421
     try:
         data = jwt.decode(args['token'],
                           scorepesa_cfgs['encrption_key'],
                           algorithms=['HS256'])
         message_json = data.get('user')
         current_app.logger.info(
             "virtual bet data extracted :::{0} ::: {1}".format(
                 message_json, data))
         if message_json:
             res = "Sorry virtual is not available now. Please check again later."
             response, status = self.virtuals_api_bet(message_json)
     except JWTError as e:
         current_app.logger.error("Virtual Bet token exception %r " % e)
     resp = make_response(response, status)
     current_app.logger.info(
         "jwt virtual bet api response message:: %r :: %r ::returned::%r" %
         (response, status, resp))
     return resp
示例#6
0
    def __init__(self, logger):
        self.logger = logger
        self.bonus_balance_amount = None
        self.db_configs = LocalConfigParser.parse_configs("DB")
        self.vtdb_configs = LocalConfigParser.parse_configs("VTDB")
        self.scorepesa_configs = LocalConfigParser.parse_configs("SCOREPESA")
        self.scorepesa_points_cfgs = LocalConfigParser.parse_configs(
            "SCOREPESAPOINT")
        self.scorepesa_freebet_cfgs = LocalConfigParser.parse_configs(
            "FREEBET")
        self.scorepesa_bonus_cfgs = LocalConfigParser.parse_configs(
            "SCOREPESABONUS")
        self.scorepesa_virtuals_cfgs = LocalConfigParser.parse_configs(
            "SCOREPESAVIRTUALS")
        self.logger.info("Scorepesa virtuals process init.....")
        self.profile_id = None
        self.stake_on_cash = None
        self.bet_transaction_id = None
        self.virtual_bet_error = None
        self.bonus, self.balance = None, None
        self.db_vt, self.db = self.db_factory()
        self.bet_string_message = ''
        self.bet_odd_total = 1.0

        super(ScorepesaVirtual, self).__init__()
示例#7
0
 def __init__(self, logger, profile_id, connection=None):
     self.logger = logger
     self.profile_id = profile_id
     self.points = None
     self.scorepesa_points_cfgs = LocalConfigParser.parse_configs("SCOREPESAPOINT")
     self.db_configs = LocalConfigParser.parse_configs("DB")
     self.scorepesa_configs = LocalConfigParser.parse_configs("SCOREPESA")
     self.scorepesa_point_trx_id = None
     self.app_name = "scorepesa_mo_consumer"
     self.db = None
     if connection is None:
        self.db = self.get_scorepesa_db()
        self.connection = self.db.engine.connect()
     else:
        self.connection = connection
     self.weekly_redeemed_points=self.check_weekly_max_points()
     self.scorepesa_points_bal, self.jp_bet_status = self.get_balance(), None
     super(ScorepesaPoint, self).__init__()
示例#8
0
    def __init__(self, logger, profile_id, connection=None):
        self.scorepesa_bonus_cfgs = LocalConfigParser.parse_configs("SCOREPESABONUS")
        self.db_configs = LocalConfigParser.parse_configs("DB")
        self.logger = logger
        self.profile_id = profile_id
        self.referal_bonus_expired = False
        self.no_referal_bonus = True
        self.referal_bonus_extra = ''
        self.bonus_adjust_to_stake = False
        self.new_bonus_balance_amount = 0.0
        self.current_bonus = None
        self.daily_bonus_claimed_notify=False
        self.daily_bonus_claimed = 0.0

        if connection is None:
           self.db = self.get_scorepesa_db()
           self.connection = self.db.engine.connect()
        else:
           self.connection = connection
        super(ReferralBonus, self).__init__()
示例#9
0
def check_auth(username, password):
    """This function is called to check if a username /
    password combination is valid.
    """
    current_app.logger.info("received creds....{0}::{1}".format(
        username, password))
    scorepesa_cfgs = LocalConfigParser.parse_configs("SCOREPESACASINO")
    passwd = scorepesa_cfgs['luckysix_api_password']
    user = scorepesa_cfgs['luckysix_api_user']
    #current_app.logger.info("config creds ...{0}::{1}".format(user, passwd))

    return str(username) == str(user) and str(password) == str(passwd)
示例#10
0
    def get(self):
        try:
            current_app.logger.info('Headers: %s', request.headers)
            current_app.logger.info('Body: {0} :: session: {1} '.format(
                request.args, request.args.get("sessionId")))
            #parser = reqparse.RequestParser()
            #current_app.logger.info('Got parser: %r', parser)
            #parser.add_argument('sessionId', type=str, required=True, help='Required missing')
            #parser.add_argument('foreignId', type=int, required=True, help='Required missing')
            #parser.add_argument('clubUuid', type=str, required=True, help='Required missing')
            args = request.args  #parser.parse_args()
            current_app.logger.info(
                'extracted arguments: {0}::session:{1}'.format(
                    args, args['sessionId']))
            scorepesa_cfgs = LocalConfigParser.parse_configs("SCOREPESA")
            current_app.logger.info(
                "check session api args :: {0} :configs: {1}".format(
                    args, scorepesa_cfgs['encrption_key']))
        except Exception as ex:
            current_app.logger.error(
                "check session invalid request...{0}".format(ex))
            args = None

        if not args or not args['sessionId']:
            response = {"isValid": False}
            return response, 200

        if not args['sessionId'] or not args['foreignId'] or not args[
                'clubUuid']:
            response = {"isValid": False}
            return response, 200

        #validate token
        tpToken = args['sessionId']
        try:
            data = jwt.decode(tpToken,
                              scorepesa_cfgs['encrption_key'],
                              algorithms=['HS256'])
            profile_id = data.get('user').get('id')
            if int(profile_id) != int(args['foreignId']):
                response = {"isValid": False}
                return response, 200
        except JWTError as e:
            current_app.logger.error("session token check exception %r " % e)
            response = {"isValid": False}
            return response, 200

        response = {"isValid": True}
        current_app.logger.info(
            "check session success response :: {0}".format(response))
        return response, 200
示例#11
0
    def post(self):
        try:
            message = request.get_json()
            current_app.logger.info(
                'resettle request message received.... {0}'.format(message))
        except Exception as ex:
            current_app.logger.error("invalid request...{0}".format(ex))
            message = None

        if not message:
            response = {
                "status": "ERROR",
                "balance": '',
                "currency": '',
                "msg": 'Failed!'
            }
            return response, 200

        session_id = None
        #validate token
        tpToken = message.get('tpToken')
        scorepesa_cfgs = LocalConfigParser.parse_configs("SCOREPESA")
        try:
            data = jwt.decode(tpToken,
                              scorepesa_cfgs['encrption_key'],
                              algorithms=['HS256'])
            session_id = data.get('session_id', '')
        except JWTError as e:
            current_app.logger.error("session token exception %r " % e)

        if not session_id:
            response = {
                "status": "INVALID_USER_TOKEN",
                "balance": '',
                "currency": '',
                "msg": 'Failed!'
            }
            return response, 200

        message['request_name'] = 'ReSettleRequest'
        current_app.logger.info(
            "Received re-settle request:::: {0}".format(message))
        casino = ScorepesaCasino(current_app.logger)
        payment_id = message.get("paymentId")
        trx_id = message.get("transactionId")
        response, status = casino.do_resettle(payment_id, trx_id)
        current_app.logger.info("class response .... {0}::{1}::::".format(
            response, status))
        return response, status
示例#12
0
    def post(self, ops='android'):
        try:
            current_app.logger.info("download request....{0}".format(ops))
            if not ops:
                return "Bad request", 400
            scorepesa_app_cfgs = LocalConfigParser.parse_configs(
                "SCOREPESAAPP")
            app_directory = scorepesa_app_cfgs['scorepesa_app_directory']

            if ops == "android":  #args.get("os") == "android":
                android_apk_name = scorepesa_app_cfgs['android_app_name']
                file_ext = scorepesa_app_cfgs['android_app_extension']
            else:
                return make_response("Sorry request failed.", 200)
            filename = '{0}.{1}'.format(android_apk_name, file_ext)
            url = scorepesa_app_cfgs[
                'app_download_url']  # user provides url in query string

            try:
                #rotate any existing app apk first for new one
                shutil.move(
                    "{0}/{1}".format(app_directory, filename),
                    "{0}/{1}.{2}".format(
                        app_directory, filename,
                        datetime.now().strftime('%Y%m%d%H%M%S')))
            except Exception, e:
                current_app.logger.error(
                    "Ignore Exception on rotating app apk.... %r " % e)

            r = requests.get(url, stream=True)
            with open(filename, 'wb') as f:
                shutil.copyfileobj(r.raw, f)

            try:
                shutil.move("{0}".format(filename),
                            "{0}/{1}".format(app_directory, filename))
            except Exception, e:
                current_app.logger.error(
                    "Exception on moving to app apk folder.... %r " % e)
                #remove the copied file to re-copy to avoid confusion on rotation
                try:
                    os.unlink(filename)
                except Exception, e:
                    current_app.logger.error(
                        "Ignoring Exception on removing copied to app apk.... %r "
                        % e)
                    pass
示例#13
0
 def get(self):
     current_app.logger.info(
         "Scorepesa mobile app check version request....")
     scorepesa_cfgs = LocalConfigParser.parse_configs("SCOREPESAAPP")
     try:
         http_code = 200
         helper = Helper(current_app.logger)
         result = helper.scorepesa_app_check_current_version()
         current_app.logger.info(
             "scorepesa app api version response .....{0}".format(result))
     except Exception as e:
         current_app.logger.error("Exception on version check ..... %r " %
                                  e)
         http_code = 400
         result = "Invalid request."
     resp = make_response(json.dumps(result), http_code)
     return resp
示例#14
0
 def router(self, args, reqparam):
     scorepesa_cfgs = LocalConfigParser.parse_configs("SCOREPESA")
     data = jwt.decode(args['token'],
                       scorepesa_cfgs['encrption_key'],
                       algorithms=['HS256'])
     self.log.info(
         "mobile apis router extracted Xposed request data..... %r" % data)
     result = None
     #routes
     if reqparam == 'outbox':
         result = self.process_api_outbox(data)
     else:
         self.log.info(
             "mobile apis oops could not understand ignored....Xposed request data [] {0} []"
             .format(data))
         return result
     return result
示例#15
0
def send_notification(msisdn, outbox_id, network, message):
    url = LocalConfigParser.parse_configs("BULK")["url"]
    try:
        sms_payload = {
            "PhoneNumber": msisdn,
            "ticketNumber": outbox_id,
            "network": network,
            "language": "sw",
            "Text": message,
        }
        current_app.logger.info("Calling URL FOR BET ACTION: (%s, %r) " %
                                (url, sms_payload))
        output = requests.get(url, params=sms_payload, timeout=30)
        current_app.logger.info("Found result from sdp call: (%s) " %
                                (output.text, ))
    except Exception as e:  # This is the correct syntax
        current_app.logger.error("Exception attempting to send "\
            "BULK MPESA message : %r :: %r " % (message, e))
示例#16
0
 def __init__(self, logger):
     super(ScorepesaSpecials, self).__init__(Scorepesa(logger))
     self.logger.info("[+] now scorepesa specials init()..")
     self.scorepesa_ussd_cfgs = LocalConfigParser.parse_configs(
         "SCOREPESASPECIALS")
示例#17
0
from celery.utils.log import get_task_logger
from celery import Celery
from celery import bootsteps
from kombu import Consumer, Queue
from utils import LocalConfigParser
from Db import Db
import json

rabbit_configs = LocalConfigParser.parse_configs("RABBIT")
sdp_configs = LocalConfigParser.parse_configs("SDP")
print "CONFIGS", rabbit_configs

host = rabbit_configs['rabbithost']
username = rabbit_configs['rabbitusername']
password = rabbit_configs['rabbitpassword']
port = rabbit_configs['rabbitport']
vhost = rabbit_configs['rabbitvhost']
sdp_url = sdp_configs["url"]
bulk_url = sdp_configs["bulk_url"]

BROKER_URL = 'amqp://{user}:{password}@{host}:{port}//'.format(
    user=username, password=password, host=host, port=port)
app = Celery('inbound_consumer', broker=BROKER_URL)

logger = get_task_logger(__name__)

queue_list = ['BulkStopQueue', 'DLRMNOQUEUE', 'NotifyMNOQUEUE', 'SyncMNOQUEUE']


class AlertConsumerStep(bootsteps.ConsumerStep):
    def get_consumers(self, channel):
示例#18
0
 def __init__(self, queue_name, exchange_name):
     self.exchange_name = exchange_name
     self.queue_name = queue_name
     self.configs = LocalConfigParser.parse_configs("RABBIT")
     self.logger = current_app.logger
     self.logger.error("COnfigs: %r" % self.configs)
示例#19
0
 def __init__(self, logger):
     super(ScorepesaUssd, self).__init__(Scorepesa(logger))
     self.logger.info("[+] now scorepesa ussd init()..")
     self.scorepesa_ussd_cfgs = LocalConfigParser.parse_configs(
         "SCOREPESAUSSD")
示例#20
0
 def __init__(self, db, logger):
     self.configs = LocalConfigParser.parse_configs("RABBIT")
     self.logger = logger
     self.db = db
示例#21
0
    def post(self):
        try:
            message = request.get_json()
            current_app.logger.info(
                'Reserve funds post body: {0} ::: '.format(message))
        except Exception as ex:
            current_app.logger.error("invalid request...{0}".format(ex))
            message = None

        if not message:
            response = {
                "status": "ERROR",
                "balance": '',
                "currency": '',
                "msg": 'Failed!'
            }
            return response, 200

        session_id = None
        #validate token
        tpToken = message.get('tpToken')
        scorepesa_cfgs = LocalConfigParser.parse_configs("SCOREPESA")
        try:
            data = jwt.decode(tpToken,
                              scorepesa_cfgs['encrption_key'],
                              algorithms=['HS256'])
            profile_id = data.get('user').get('id')
        except JWTError as e:
            current_app.logger.error("session token exception %r " % e)
            response = {
                "status": "INVALID_USER_TOKEN",
                "balance": '',
                "currency": '',
                "msg": 'Failed!'
            }
            return response, 200

        if not profile_id:
            response = {
                "status": "INVALID_USER_TOKEN",
                "balance": '',
                "currency": '',
                "msg": 'Failed!'
            }
            return response, 200

        message['request_name'] = 'ReserveFunds'
        message['profile_id'] = profile_id
        current_app.logger.info(
            "Received reserve funds request:::: {0}".format(message))
        casino = ScorepesaCasino(current_app.logger)
        aggregator_id, trx_id, status, balance = casino.create_seven_aggregator_request(
            message, request_type=0)
        msg_status = "OK"
        currency = "KES"
        bal = balance
        msg = ""
        current_app.logger.info(
            "class response .... {0}::{1}::{2}::{3}".format(
                aggregator_id, trx_id, status, balance))
        if not aggregator_id or not trx_id:
            msg_status = "ERROR"
            currency = ""
            bal = ""
            msg = "Failed."
            status = 200
        if balance == 0:
            msg = "Insufficient balance"
            msg_status = "INSUFFICIENT_FUNDS"
        if balance == -1:
            msg = "User not found."
            msg_status = "USER_SUSPENDED"
        if balance == -2:
            msg = "Not Allowed."
            msg_status = "200"

        response = {
            "status": msg_status,
            "balance": bal,
            "currency": currency,
            "msg": msg
        }

        return response, status
示例#22
0
    def get(self):
        try:
            current_app.logger.info('Headers: %s', request.headers)
            current_app.logger.info('Body: {0} :: session: {1} '.format(
                request.args, request.args.get("sessionId")))
            #sessionId=$sessionId&foreignId=$foreignId&clubUuid=$clubUuid
            #parser = reqparse.RequestParser()
            #parser.add_argument('sessionId', type=str, required=True, help='Required missing')
            #parser.add_argument('foreignId', type=int, required=True, help='Required missing')
            #parser.add_argument('clubUuid', type=str, required=True, help='Required missing')
            args = request.args  #parser.parse_args()
            scorepesa_cfgs = LocalConfigParser.parse_configs("SCOREPESA")
            current_app.logger.info(
                "player detail api args :: {0} :configs: {1} ::session: {2}".
                format(args, scorepesa_cfgs['encrption_key'],
                       args.get("sessionId")))
            response = u'Invalid request.'
            status = 421
        except Exception as ex:
            current_app.logger.error("invalid request...{0}".format(ex))
            args = None

        if not args or not args.get('sessionId'):
            response = {
                "status": "ERROR",
                "balance": '',
                "currency": '',
                "msg": 'Failed!'
            }
            return response, 200

        #validate token
        tpToken = args.get('sessionId')
        scorepesa_cfgs = LocalConfigParser.parse_configs("SCOREPESA")
        try:
            data = jwt.decode(tpToken,
                              scorepesa_cfgs['encrption_key'],
                              algorithms=['HS256'])
            user = data.get('user')
            profile_id = user.get('id')
        except JWTError as e:
            current_app.logger.error("session token exception %r " % e)
            response = {
                "status": "INVALID_USER_TOKEN",
                "balance": '',
                "currency": '',
                "msg": 'Failed!'
            }
            return response, 200

        if not profile_id:
            response = {
                "status": "INVALID_USER_TOKEN",
                "balance": '',
                "currency": '',
                "msg": 'Failed!'
            }
            return response, 200
        try:
            args = args.to_dict()
            args['request_name'] = 'PlayerDetailRequest'
            current_app.logger.info(
                "Received player detail request:::: {0}".format(args))
            casino = ScorepesaCasino(current_app.logger)
            profile_id = args['foreignId']
            response, status = casino.get_player_detail(profile_id)
            current_app.logger.info(
                "player detail class response .... {0}::{1}::::".format(
                    response, status))
        except Exception as Ex:
            current_app.logger.error(
                "exception processing player detail...{0}".format(Ex))
            response = {
                "status": "ERROR",
                "balance": '',
                "currency": '',
                "msg": 'Failed'
            }
            status = 200
        return response, status
示例#23
0
 def __init__(self, queue_name, exchange_name):
     self.exchange_name = exchange_name
     self.queue_name = queue_name
     self.configs = LocalConfigParser.parse_configs("RABBIT")
     self.sdp_configs = LocalConfigParser.parse_configs("SDP")
     self.logger = current_app.logger