Exemple #1
0
def addAnswer():
    try:

        data = request.json

        

        if data is None:
            return response_error(MESSAGE.INVALID_PARAMETER, CODE.INVALID_PARAMETER)


        bm_id = data['bm_id']
        questions = data['question']
        user_id = get_jwt_identity()

        if len(questions) == 0:
            return response_error(MESSAGE.EMPTY_QUESTION, CODE.EMPTY_QUESTION)

        for q in questions:
            answer = Answer(
                bm_id=bm_id,
                answer=q['answer'],
                question_id=q['id'],
                user_id=user_id
            )
            db.session.add(answer)
            db.session.commit()
            
            
        return response_ok()
    except Exception as ex:
        db.session.rollback()
        return response_error(str(ex))
def review_market(market_id):
	"""
	" Admin approve/reject user market.
	"""
	try:
		data = request.json
		outcome_id = data.get("outcome_id", -1)
		status = data.get("status", CONST.OUTCOME_STATUS['APPROVED'])

		match = None
		if outcome_id == -1:
			match = Match.find_match_by_id(market_id)
			if match is not None:
				for o in match.outcomes:
					if o.approved == CONST.OUTCOME_STATUS['PENDING'] and o.hid is None:
						o.approved = status
						db.session.flush()

				if status == CONST.OUTCOME_STATUS['APPROVED']:
					task = admin_bl.add_create_market_task(match)
					if task is not None:				
						db.session.add(task)
						db.session.flush()
					else:
						return response_error(MESSAGE.CONTRACT_EMPTY_VERSION, CODE.CONTRACT_EMPTY_VERSION)
				else:
					send_email_event_verification_failed.delay(match.id, match.created_user_id)

			else:
				return response_error(MESSAGE.MATCH_NOT_FOUND, CODE.MATCH_NOT_FOUND)

		else:
			outcome = db.session.query(Outcome).filter(and_(Outcome.id==outcome_id, Outcome.match_id==market_id)).first()
			if outcome is None:
				return response_error(MESSAGE.OUTCOME_INVALID, CODE.OUTCOME_INVALID)

			if outcome.approved == CONST.OUTCOME_STATUS['PENDING'] and outcome.hid is None:
				outcome.approved = status
				db.session.flush()

				match = outcome.match
				if status == CONST.OUTCOME_STATUS['APPROVED']:
					task = admin_bl.add_create_market_task(match)
					if task is not None:				
						db.session.add(task)
						db.session.flush()
					else:
						return response_error(MESSAGE.CONTRACT_EMPTY_VERSION, CODE.CONTRACT_EMPTY_VERSION)
						
				else:
					send_email_event_verification_failed.delay(match.id, match.created_user_id)

			else:
				return response_error(MESSAGE.MATCH_HAS_BEEN_REVIEWED, CODE.MATCH_HAS_BEEN_REVIEWED)

		db.session.commit()
		return response_ok(match.to_json())
	except Exception, ex:
		db.session.rollback()
		return response_error(ex.message)
def matches_need_resolve_by_admin():
	try:
		response = []
		matches = []

		t = datetime.now().timetuple()
		seconds = local_to_utc(t)

		matches_disputed = db.session.query(Match).filter(Match.id.in_(db.session.query(Outcome.match_id).filter(and_(Outcome.result == CONST.RESULT_TYPE['DISPUTED'], Outcome.hid != None)).group_by(Outcome.match_id))).order_by(Match.date.asc(), Match.index.desc()).all()

		for match in matches_disputed:
			match_json = match.to_json()
			arr_outcomes = []
			for outcome in match.outcomes:
				if outcome.result == CONST.RESULT_TYPE['DISPUTED']:
					outcome_json = outcome.to_json()
					arr_outcomes.append(outcome_json)

			if len(arr_outcomes) > 0:
				match_json["outcomes"] = arr_outcomes if len(arr_outcomes) > 0 else []
				response.append(match_json)

		return response_ok(response)
	except Exception, ex:
		return response_error(ex.message)
Exemple #4
0
def auth():
    try:
        data = request.json
        if data is None or 'email' not in data:
            return response_error(MESSAGE.INVALID_DATA, CODE.INVALID_DATA)

        email = data['email']
        password = data['password']
        if is_valid_email(email) == False:
            return response_error(MESSAGE.USER_INVALID_EMAIL,
                                  CODE.USER_INVALID_EMAIL)

        if is_valid_password(password) == False:
            return response_error(MESSAGE.USER_INVALID_PASSWORD,
                                  CODE.USER_INVALID_PASSWORD)

        password = hashlib.md5(password).hexdigest()
        u = User.find_user_by_email_and_password(email, password)
        if u is not None:
            response = u.to_json()
            response['access_token'] = create_access_token(identity=email,
                                                           fresh=True)
            return response_ok(response)

        return response_error(MESSAGE.USER_INVALID, CODE.USER_INVALID)
    except Exception, ex:
        db.session.rollback()
        return response_error(ex.message)
Exemple #5
0
def user_approve_new_token():
    """
	" Add token that approved by user. It's used for ERC20 function.
	"""
    try:
        data = request.json
        if data is None or \
         'token_id' not in data:
            return response_error(MESSAGE.INVALID_DATA, CODE.INVALID_DATA)

        uid = int(request.headers['Uid'])
        token_id = data['token_id']

        token = Token.find_token_by_id(token_id)
        if token is None or \
         token.tid is None or \
         token.status == -1:
            return response_error(MESSAGE.TOKEN_NOT_FOUND,
                                  CODE.TOKEN_NOT_FOUND)

        user = User.find_user_with_id(uid)

        if token not in user.tokens:
            user.tokens.append(token)
        else:
            return response_error(MESSAGE.TOKEN_APPROVED_ALREADY,
                                  CODE.TOKEN_APPROVED_ALREADY)

        db.session.commit()
        return response_ok(user.to_json())

    except Exception, ex:
        db.session.rollback()
        return response_error(ex.message)
Exemple #6
0
def user_hook():
    try:
        data = request.json
        print "Hook data: {}".format(data)
        if data is None:
            return response_error(MESSAGE.INVALID_DATA, CODE.INVALID_DATA)

        type_change = data.get('type_change', None)
        user_id = data.get('user_id', None)
        email = data.get('email', None)
        meta_data = data.get('meta_data', None)
        name = data.get('name', None)

        if type_change == "Update":
            user = User.find_user_with_id(user_id)

            if user is not None:
                if user.email != email and email is not None and email != "":
                    print "Update email: {}".format(email)
                    user.email = email
                    db.session.flush()

                if user.name != name and name is not None and name != "":
                    print "Update name: {}".format(name)
                    user.name = name
                    db.session.flush()

        db.session.commit()
        return response_ok()

    except Exception, ex:
        db.session.rollback()
        return response_error(ex.message)
def ninja_predict():
    try:
        uid = int(request.headers['Uid'])
        data = request.json
        if data is None:
            return response_error(MESSAGE.INVALID_DATA, CODE.INVALID_DATA)

        outcome_id = data['outcome_id']
        outcome = db.session.query(Outcome).filter(
            and_(Outcome.id == outcome_id)).first()
        if outcome is not None:
            response = {}
            response[
                'support'] = outcome_bl.count_support_users_play_on_outcome(
                    outcome_id)
            response[
                'oppose'] = outcome_bl.count_against_users_play_on_outcome(
                    outcome_id)
            return response_ok(response)

        else:
            return response_error(MESSAGE.OUTCOME_INVALID,
                                  CODE.OUTCOME_INVALID)

    except Exception, ex:
        return response_error(ex.message)
def refund():
	"""
	"	Refund real bet:
	"		This step make sure user's feed will update pending status
	"""
	try:
		uid = int(request.headers['Uid'])
		user = User.find_user_with_id(uid)

		data = request.json
		if data is None:
			return response_error(MESSAGE.INVALID_DATA, CODE.INVALID_DATA)

		offchain = data.get('offchain', '')
		if len(offchain) == 0:
			return response_error(MESSAGE.MISSING_OFFCHAIN, CODE.MISSING_OFFCHAIN)

		offchain = offchain.replace(CONST.CRYPTOSIGN_OFFCHAIN_PREFIX, '')
		outcome = None
		if 'm' in offchain:
			offchain = int(offchain.replace('m', ''))
			handshake = db.session.query(Handshake).filter(and_(Handshake.id==offchain, Handshake.user_id==user.id)).first()
			if handshake is None:
				return response_error(MESSAGE.HANDSHAKE_CANNOT_REFUND, CODE.HANDSHAKE_CANNOT_REFUND)

			outcome = Outcome.find_outcome_by_id(handshake.outcome_id)

		elif 's' in offchain:
			offchain = int(offchain.replace('s', ''))
			shaker = db.session.query(Shaker).filter(and_(Shaker.id==offchain, Shaker.shaker_id==user.id)).first()
			if shaker is None:
				return response_error(MESSAGE.HANDSHAKE_CANNOT_REFUND, CODE.HANDSHAKE_CANNOT_REFUND)

			handshake = Handshake.find_handshake_by_id(shaker.handshake_id)
			outcome = Outcome.find_outcome_by_id(handshake.outcome_id)


		if outcome is None:
			return response_error(MESSAGE.OUTCOME_INVALID, CODE.OUTCOME_INVALID)

		handshakes = db.session.query(Handshake).filter(and_(Handshake.status.in_([HandshakeStatus['STATUS_INITED'], HandshakeStatus['STATUS_RESOLVED']]), Handshake.user_id==user.id, Handshake.outcome_id==outcome.id)).all()
		shakers = db.session.query(Shaker).filter(and_(Shaker.status.in_([HandshakeStatus['STATUS_SHAKER_SHAKED'], HandshakeStatus['STATUS_RESOLVED']]), Shaker.shaker_id==user.id, Shaker.handshake_id.in_(db.session.query(Handshake.id).filter(Handshake.outcome_id==outcome.id)))).all()

		for h in handshakes:
			h.bk_status = h.status
			h.status = HandshakeStatus['STATUS_REFUND_PENDING']
			db.session.merge(h)

		for s in shakers:
			s.bk_status = s.status
			s.status = HandshakeStatus['STATUS_REFUND_PENDING']
			db.session.merge(s)
			
		db.session.commit()
		handshake_bl.update_handshakes_feed(handshakes, shakers)

		return response_ok()
	except Exception, ex:
		db.session.rollback()
		return response_error(ex.message)
Exemple #9
0
def login():
    """
    "   user login based on [email] and [password]
    """
    data = request.json
    if data is None:
        return response_error(MESSAGE.INVALID_PARAMETER,
                              CODE.INVALID_PARAMETER)

    email = data['email']
    password = data['password']

    if is_valid_email(email) == False:
        return response_error(MESSAGE.INVALID_EMAIL, CODE.INVALID_EMAIL)

    user = User.find_by_email(email)
    if user is None:
        return response_error(MESSAGE.USER_NOT_FOUND, CODE.USER_NOT_FOUND)

    candidate_password = hashlib.md5('{}{}'.format(password.strip(),
                                                   'appscyclone')).hexdigest()
    hashed_password = user.password

    if hashed_password != candidate_password:
        return response_error(MESSAGE.PASSWORD_NOT_MATCH,
                              CODE.PASSWORD_NOT_MATCH)

    return response_ok(create_access_token(identity=user.id, fresh=True))
def matches_need_report_by_admin():
	try:
		response = []
		matches = []

		t = datetime.now().timetuple()
		seconds = local_to_utc(t)

		matches_by_admin = db.session.query(Match).filter(\
														Match.date < seconds, \
														Match.reportTime >= seconds, \
														Match.id.in_(db.session.query(Outcome.match_id).filter(and_(\
																													Outcome.result == -1, \
																													Outcome.hid != None))\
																										.group_by(Outcome.match_id))) \
													.order_by(Match.date.asc(), Match.index.desc()).all()

		for match in matches_by_admin:
			match_json = match.to_json()
			arr_outcomes = []
			for outcome in match.outcomes:
				if admin_bl.can_admin_report_this_outcome(outcome):
					arr_outcomes.append(outcome.to_json())

			if len(arr_outcomes) > 0:
				match_json["outcomes"] = arr_outcomes
				response.append(match_json)

		return response_ok(response)
	except Exception, ex:
		return response_error(ex.message)
Exemple #11
0
def update_question_for_type(question_id):
	"""
	"	admin change question name for type
	"""
	try:
		review_type = request.args.get('type', '')
		if len(review_type) == 0:
			return response_error(MESSAGE.TYPE_INVALID, CODE.TYPE_INVALID)
		
		t = db.session.query(ReviewType).filter(ReviewType.name==func.binary(review_type)).first()
		if t is None:
			return response_error(MESSAGE.TYPE_INVALID, CODE.TYPE_INVALID)

		question = db.session.query(Question).filter(Question.id==question_id, Question.type_id==t.id).first()
		if question is None:
			return response_error(MESSAGE.QUESTION_NOT_EXIST, CODE.QUESTION_NOT_EXIST)

		if request.method == 'PUT':
			data = request.json
			if data is None:
				return response_error(MESSAGE.INVALID_DATA, CODE.INVALID_DATA)

			name = data.get('name', '')
			question.name = name

		else:
			db.session.delete(question)

		db.session.commit()
		return response_ok()
	except Exception, ex:
		db.session.rollback()
		return response_error(ex.message)
Exemple #12
0
def auth():
    try:
        data = request.json
        if data is None or 'email' not in data:
            return response_error(MESSAGE.INVALID_DATA, CODE.INVALID_DATA)

        email = data['email']
        password = data['password']

        confirm = hashlib.md5('{}{}'.format(email.strip(),
                                            g.PASSPHASE)).hexdigest()
        if email == g.EMAIL and password == confirm:
            response = {}
            if is_valid_email(email):
                response['access_token'] = create_access_token(identity=email,
                                                               fresh=True)
            else:
                return response_error(MESSAGE.USER_INVALID_EMAIL,
                                      CODE.USER_INVALID_EMAIL)

            return response_ok(response)

        else:
            return response_error(MESSAGE.USER_INVALID, CODE.USER_INVALID)

    except Exception, ex:
        db.session.rollback()
        return response_error(ex.message)
Exemple #13
0
def add_quesion_for_type():
	"""
	"	admin will add questions for object type which need to be reviewed
	"""
	try:
		data = request.json
		if data is None:
			return response_error(MESSAGE.INVALID_DATA, CODE.INVALID_DATA)

		review_type = request.args.get('type', '')
		if len(review_type) == 0:
			return response_error(MESSAGE.TYPE_INVALID, CODE.TYPE_INVALID)

		t = db.session.query(ReviewType).filter(ReviewType.name==func.binary(review_type)).first()
		if t is None:
			return response_error(MESSAGE.TYPE_INVALID, CODE.TYPE_INVALID)

		for d in data:
			if 'name' in d:
				question = Question(
					name=d['name'],
					type_id=t.id
				)
				db.session.add(question)
				db.session.flush()

		db.session.commit()
		return response_ok()
	except Exception, ex:
		db.session.rollback()
		return response_error(ex.message)
Exemple #14
0
def add():
    try:
        uid = int(request.headers['Uid'])
        data = request.json
        if data is None:
            return response_error(MESSAGE.INVALID_DATA, CODE.INVALID_DATA)

        response_json = []
        for item in data:
            token = Token(symbol=item['symbol'],
                          name=item['name'],
                          decimal=int(item['decimal']),
                          contract_address=item['contract_address'],
                          created_user_id=uid)
            db.session.add(token)
            db.session.flush()

            task = Task(task_type=CONST.TASK_TYPE['ERC_20'],
                        data=json.dumps(token.to_json()),
                        action=CONST.TASK_ACTION['ADD_TOKEN'],
                        status=-1,
                        contract_address=g.ERC20_TOKEN_REGISTRY_SMART_CONTRACT,
                        contract_json=g.ERC20_TOKEN_REGISTRY_JSON)
            db.session.add(task)
            db.session.flush()

            response_json.append(token.to_json())

        db.session.commit()
        return response_ok(response_json)
    except Exception, ex:
        db.session.rollback()
        return response_error(ex.message)
Exemple #15
0
def approve(id):
    try:
        # set status = 1
        # call bc: approve new token
        token = db.session.query(Token).filter(Token.id == id).first()
        if token is None:
            return response_error(MESSAGE.TOKEN_NOT_FOUND,
                                  CODE.TOKEN_NOT_FOUND)

        if token.status == CONST.TOKEN_STATUS['APPROVED']:
            return response_error(MESSAGE.TOKEN_APPROVED_ALREADY,
                                  CODE.TOKEN_APPROVED_ALREADY)

        token.status = CONST.TOKEN_STATUS['APPROVED']
        db.session.merge(token)

        # add offchain
        data = token.to_json()
        data[
            'offchain'] = CONST.CRYPTOSIGN_ERC20_OFFCHAIN_PREFIX + 'token{}'.format(
                token.id)
        task = Task(task_type=CONST.TASK_TYPE['ERC_20'],
                    data=json.dumps(data),
                    action=CONST.TASK_ACTION['APPROVE_TOKEN'],
                    status=-1,
                    contract_address=g.ERC20_PREDICTION_SMART_CONTRACT,
                    contract_json=g.ERC20_PREDICTION_JSON)
        db.session.add(task)
        db.session.commit()

        return response_ok(message="{} has been approved!".format(token.name))
    except Exception, ex:
        db.session.rollback()
        return response_error(ex.message)
Exemple #16
0
def add():
    try:
        data = request.json
        if data is None:
            return response_error(MESSAGE.INVALID_DATA, CODE.INVALID_DATA)

        response_json = []
        for item in data:
            tx = Tx(hash=item['hash'],
                    offchain=item['offchain'],
                    payload=item['payload'],
                    contract_address=item['contract_address'],
                    contract_method=item['contract_method'],
                    chain_id=item['chain_id'])
            db.session.add(tx)
            db.session.flush()

            response_json.append(tx.to_json())

        db.session.commit()

        return response_ok(response_json)
    except Exception, ex:
        db.session.rollback()
        return response_error(ex.message)
Exemple #17
0
def crud(role_id):
    try:

        role = Role.find_role_by_id(role_id)
        if role is None:
            return response_error(MESSAGE.ROLE_NOT_FOUND, CODE.ROLE_NOT_FOUND)

        if request.method == 'PUT':
            data = request.json
            if data is None:
                return response_error(MESSAGE.INVALID_DATA, CODE.INVALID_DATA)

            if 'name' in data and data['name'].lower() in CONST.ROLES:
                role.name = data['name'].lower()
                db.session.flush()

            else:
                return response_error(MESSAGE.ROLE_INVALID, CODE.ROLE_INVALID)

        else:
            db.session.delete(role)

        db.session.commit()
        return response_ok()
    except Exception, ex:
        db.session.rollback()
        return response_error(ex.message)
def refund_free_bet():
	"""
	"	Refund free-bet in ETH
	"""
	try:
		uid = int(request.headers['Uid'])
		chain_id = int(request.headers.get('ChainId', CONST.BLOCKCHAIN_NETWORK['RINKEBY']))
		user = User.find_user_with_id(uid)

		data = request.json
		if data is None:
			return response_error(MESSAGE.INVALID_DATA, CODE.INVALID_DATA)

		offchain = data.get('offchain', '')
		if len(offchain) == 0:
			return response_error(MESSAGE.MISSING_OFFCHAIN, CODE.MISSING_OFFCHAIN)

		handshakes = []
		shakers = []

		offchain = offchain.replace(CONST.CRYPTOSIGN_OFFCHAIN_PREFIX, '')
		if 's' in offchain:
			offchain = int(offchain.replace('s', ''))
			shaker = db.session.query(Shaker).filter(and_(Shaker.id==offchain, Shaker.shaker_id==user.id)).first()
			if handshake_bl.can_refund(None, shaker=shaker):
				shaker.bk_status = shaker.status
				shaker.status = HandshakeStatus['STATUS_REFUNDED']
				db.session.merge(shaker)
				db.session.flush()
				shakers.append(shaker)

			else:
				return response_error(MESSAGE.HANDSHAKE_CANNOT_REFUND, CODE.HANDSHAKE_CANNOT_REFUND)

		elif 'm' in offchain:
			offchain = int(offchain.replace('m', ''))
			handshake = db.session.query(Handshake).filter(and_(Handshake.id==offchain, Handshake.user_id==user.id)).first()
			if handshake_bl.can_refund(handshake):
				handshake.bk_status = handshake.status
				handshake.status = HandshakeStatus['STATUS_REFUNDED']
				db.session.merge(handshake)
				db.session.flush()
				handshakes.append(handshake)

			else:
				return response_error(MESSAGE.HANDSHAKE_CANNOT_REFUND, CODE.HANDSHAKE_CANNOT_REFUND)
			
		else:
			return response_error(MESSAGE.HANDSHAKE_NOT_FOUND, CODE.HANDSHAKE_NOT_FOUND)	

		db.session.commit()

		# update feed
		handshake_bl.update_handshakes_feed(handshakes, shakers)
		
		return response_ok()
	except Exception, ex:
		db.session.rollback()
		return response_error(ex.message)
def list_business_model():

    bms = BusinessModel.query.all()

    arr = []
    for bm in bms:
        arr.append(bm.to_json())

    return response_ok(arr)
Exemple #20
0
def list_question():

    questions = Question.get_list_question()

    arr = []
    for question in questions:
        arr.append(question.to_json())

    return response_ok(arr)
Exemple #21
0
def tx():
    try:
        txs = db.session.query(Tx).all()
        response = []
        for tx in txs:
            response.append(tx.to_json())
        return response_ok(response)
    except Exception, ex:
        return response_error(ex.message)
Exemple #22
0
def import_user():
    try:
        users = user_bl.read_data()
        db.session.bulk_save_objects(users)
        return response_ok()

    except Exception, ex:
        db.session.rollback()
        return response_error(ex.message)
Exemple #23
0
def user_subscribe():
    """
	" 3 use cases:
	" Popup subscribe email will appear after user plays on match_id.
	" Popup subscribe email will appear at the first time.
	" Popup subscribe email will apear when user click on referral link.
	"""
    try:
        data = request.json
        if data is None:
            return response_error(MESSAGE.INVALID_DATA, CODE.INVALID_DATA)

        if 'email' not in data or is_valid_email(data["email"]) is False:
            return response_error(MESSAGE.USER_INVALID_EMAIL,
                                  CODE.USER_INVALID_EMAIL)

        if user_bl.is_email_subscribed(data['email']):
            return response_error(MESSAGE.EMAIL_ALREADY_SUBSCRIBED,
                                  CODE.EMAIL_ALREADY_SUBSCRIBED)

        match = Match.find_match_by_id(data.get('match_id', -1))
        email = data["email"]
        uid = int(request.headers["Uid"])
        referral_code = data.get('referral_code', None)

        user = User.find_user_with_id(uid)
        user.email = email
        user.is_user_disable_popup = 0
        user.is_subscribe = 1

        if referral_code is not None:
            r = Referral.find_referral_by_code(referral_code)
            if r is not None and r.user_id != uid:
                user.invited_by_user = r.user_id

        db.session.flush()

        # issue referral code for user if any
        referral_bl.issue_referral_code_for_user(user)
        db.session.commit()

        # send email
        result, code_1, code_2 = user_bl.claim_redeem_code_for_user(user)
        if result:
            subscribe_email_to_claim_redeem_code.delay(
                email, code_1, code_2, request.headers["Fcm-Token"],
                request.headers["Payload"], uid)
        elif match is not None:
            subscribe_email.delay(email, match.id,
                                  request.headers["Fcm-Token"],
                                  request.headers["Payload"], uid)

        return response_ok(user.to_json())

    except Exception, ex:
        db.session.rollback()
        return response_error(ex.message)
def dispute():
	"""
	"	Dispute real bet:
	"		This step make sure user's feed will update pending status
	"""
	try:
		handshakes = []
		shakers = []
		uid = int(request.headers['Uid'])
		user = User.find_user_with_id(uid)
		data = request.json
		if data is None:
			return response_error(MESSAGE.INVALID_DATA, CODE.INVALID_DATA)

		offchain = data.get('offchain', '')
		if len(offchain) == 0:
			return response_error(MESSAGE.MISSING_OFFCHAIN, CODE.MISSING_OFFCHAIN)

		offchain = offchain.replace(CONST.CRYPTOSIGN_OFFCHAIN_PREFIX, '')

		if 'm' in offchain:
			offchain = int(offchain.replace('m', ''))
			handshake = db.session.query(Handshake).filter(and_(Handshake.id==offchain, Handshake.user_id==user.id)).first()
			if handshake is None:
				return response_error(MESSAGE.HANDSHAKE_CANNOT_REFUND, CODE.HANDSHAKE_CANNOT_REFUND)

			# check: handshake didn't match with any shaker
			if handshake.remaining_amount >= handshake.amount:
				return response_error(MESSAGE.HANDSHAKE_CANNOT_DISPUTE, CODE.HANDSHAKE_CANNOT_DISPUTE)

			handshake.bk_status = handshake.status
			handshake.status = HandshakeStatus['STATUS_DISPUTE_PENDING']
			db.session.flush()
			handshakes.append(handshake)

		elif 's' in offchain:
			offchain = int(offchain.replace('s', ''))
			shaker = db.session.query(Shaker).filter(and_(Shaker.id==offchain, Shaker.shaker_id==user.id)).first()
			if shaker is None:
				return response_error(MESSAGE.HANDSHAKE_CANNOT_REFUND, CODE.HANDSHAKE_CANNOT_REFUND)

			shaker.bk_status = shaker.status
			shaker.status = HandshakeStatus['STATUS_DISPUTE_PENDING']
			db.session.flush()
			shakers.append(shaker)
			handshake = Handshake.find_handshake_by_id(shaker.handshake_id)
			if handshake is None:
				return response_error(MESSAGE.HANDSHAKE_CANNOT_REFUND, CODE.HANDSHAKE_CANNOT_REFUND)

		db.session.commit()
		handshake_bl.update_handshakes_feed(handshakes, shakers)

		return response_ok()
	except Exception, ex:
		db.session.rollback()
		return response_error(ex.message)
def outcomes():
    try:
        outcomes = Outcome.query.order_by(desc(Outcome.index)).all()
        data = []
        for outcome in outcomes:
            data.append(outcome.to_json())

        return response_ok(data)
    except Exception, ex:
        return response_error(ex.message)
Exemple #26
0
def all_types():
    try:
        rs = db.session.query(ReviewType).all()
        response = []
        for r in rs:
            response.append(r.to_json())

        return response_ok(response)
    except Exception, ex:
        return response_error(ex.message)
Exemple #27
0
def report_match(match_id):
    """
	"" report: report outcomes
	"" input:
	""		match_id
	"""
    try:
        uid = int(request.headers['Uid'])
        data = request.json
        response = []
        if data is None:
            return response_error(MESSAGE.INVALID_DATA, CODE.INVALID_DATA)

        match = Match.find_match_by_id(match_id)
        if match is not None:
            result = data['result']
            if result is None:
                return response_error(MESSAGE.MATCH_RESULT_EMPTY,
                                      CODE.MATCH_RESULT_EMPTY)

            if not match_bl.is_exceed_closing_time(match.id):
                return response_error(MESSAGE.MATCH_CANNOT_SET_RESULT,
                                      CODE.MATCH_CANNOT_SET_RESULT)

            for item in result:
                if 'side' not in item:
                    return response_error(MESSAGE.OUTCOME_INVALID_RESULT,
                                          CODE.OUTCOME_INVALID_RESULT)

                if 'outcome_id' not in item:
                    return response_error(MESSAGE.OUTCOME_INVALID,
                                          CODE.OUTCOME_INVALID)

                outcome = Outcome.find_outcome_by_id(item['outcome_id'])
                if outcome is not None and outcome.created_user_id == uid:
                    message, code = match_bl.is_able_to_set_result_for_outcome(
                        outcome)
                    if message is not None and code is not None:
                        return message, code

                    outcome.result = CONST.RESULT_TYPE['PROCESSING']
                    outcome_json = outcome.to_json()
                    response.append(outcome_json)

                else:
                    return response_error(MESSAGE.OUTCOME_INVALID,
                                          CODE.OUTCOME_INVALID)

            return response_ok(response)
        else:
            return response_error(MESSAGE.MATCH_NOT_FOUND,
                                  CODE.MATCH_NOT_FOUND)

    except Exception, ex:
        return response_error(ex.message)
def add(match_id):
    """
	""	Add outcome to match
	"" 	Inputs:
	""		match_id
	""	Outputs:
	""		match json with contract address for frontend
	"""
    try:
        from_request = request.headers.get('Request-From', 'mobile')
        uid = int(request.headers['Uid'])

        data = request.json
        if data is None:
            return response_error(MESSAGE.INVALID_DATA, CODE.INVALID_DATA)

        match = Match.find_match_by_id(match_id)
        if match is None:
            return response_error(MESSAGE.MATCH_NOT_FOUND,
                                  CODE.MATCH_NOT_FOUND)

        contract = contract_bl.get_active_smart_contract()
        if contract is None:
            return response_error(MESSAGE.CONTRACT_EMPTY_VERSION,
                                  CODE.CONTRACT_EMPTY_VERSION)

        outcomes = []
        response_json = []
        for item in data:
            outcome = Outcome(name=item['name'],
                              match_id=match_id,
                              modified_user_id=uid,
                              created_user_id=uid,
                              contract_id=contract.id,
                              from_request=from_request,
                              approved=CONST.OUTCOME_STATUS['PENDING'])
            db.session.add(outcome)
            db.session.flush()

            outcomes.append(outcome)
            outcome_json = outcome.to_json()
            # Return match_id for client add outcome
            outcome_json["match_id"] = match_id
            outcome_json["contract"] = contract.to_json()

            response_json.append(outcome_json)

        db.session.add_all(outcomes)
        db.session.commit()

        return response_ok(response_json)

    except Exception, ex:
        db.session.rollback()
        return response_error(ex.message)
Exemple #29
0
def cates():
    try:
        categories = Category.query.all()
        data = []

        for cate in categories:
            data.append(cate.to_json())

        return response_ok(data)
    except Exception, ex:
        return response_error(ex.message)
def settings():
    try:
        settings = Setting.query.all()
        data = []

        for setting in settings:
            data.append(setting.to_json())

        return response_ok(data)
    except Exception, ex:
        return response_error(ex.message)