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)
Example #2
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)
Example #3
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 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)
def remove(id):
	try:
		contract = db.session.query(Contract).filter(Contract.id==id).first()
		if contract is not None:
			db.session.delete(contract)
			db.session.commit()
			return response_ok(message="{} has been deleted!".format(contract.id))
		else:
			return response_error(MESSAGE.INVALID_DATA, CODE.INVALID_DATA)

	except Exception, ex:
		db.session.rollback()
		return response_error(ex.message)
Example #6
0
    def wrap(*args, **kwargs):
        try:
            user_id = get_jwt_identity()
            user = User.find_by_id(user_id)

            if user is None or user.role_id != USER_ROLE['ADMINISTRATOR']:
                return response_error(MESSAGE.INVALID_PERMISSION,
                                      CODE.INVALID_PERMISSION)

        except Exception as ex:
            return response_error(str(ex))

        return f(*args, **kwargs)
Example #7
0
def delete_user(user_id):
    try:
        u = User.find_user_by_id(user_id)
        if u is None:
            return response_error(MESSAGE.USER_INVALID, CODE.USER_INVALID)

        db.session.delete(u)
        db.session.commit()
        return response_ok()

    except Exception, ex:
        db.session.rollback()
        return response_error(ex.message)
Example #8
0
def remove(id):
    try:
        token = db.session.query(Token).filter(Token.id == id).first()
        if token is not None:
            token.deleted = 1
            db.session.commit()
        else:
            return response_error(MESSAGE.TOKEN_NOT_FOUND,
                                  CODE.TOKEN_NOT_FOUND)

        return response_ok(message="{} has been deleted!".format(token.name))
    except Exception, ex:
        db.session.rollback()
        return response_error(ex.message)
Example #9
0
def remove(id):
    try:
        match = Match.find_match_by_id(id)
        if match is not None:
            db.session.delete(match)
            db.session.commit()
            return response_ok(message="{} has been deleted!".format(match.id))
        else:
            return response_error(MESSAGE.MATCH_NOT_FOUND,
                                  CODE.MATCH_NOT_FOUND)

    except Exception, ex:
        db.session.rollback()
        return response_error(ex.message)
def detail(id):
	uid = int(request.headers['Uid'])
	chain_id = int(request.headers.get('ChainId', CONST.BLOCKCHAIN_NETWORK['RINKEBY']))
	user = User.find_user_with_id(uid)		

	try:
		handshake = db.session.query(Handshake).filter(and_(Handshake.id==id, Handshake.user_id==uid)).first()
		if handshake is not None:
			return response_ok(handshake.to_json())

		return response_error(MESSAGE.HANDSHAKE_NOT_FOUND, CODE.HANDSHAKE_NOT_FOUND)

	except Exception, ex:
		return response_error(ex.message)
def remove(id):
    try:
        setting = Setting.find_setting_by_id(id)
        if setting is not None:
            db.session.delete(setting)
            db.session.commit()
            return response_ok(
                message="{} has been deleted!".format(setting.id))
        else:
            return response_error(MESSAGE.INVALID_DATA, CODE.INVALID_DATA)

    except Exception, ex:
        db.session.rollback()
        return response_error(ex.message)
Example #12
0
    def wrap(*args, **kwargs):
        current_user = get_jwt_identity()
        user = db.session.query(User).filter(
            User.email == func.binary(current_user)).first()

        if user is None or \
            user.role is None or \
            user.role.name is None:
            return response_error("Access deny!")

        if user.role.name != Role['HR'] and \
            user.role.name != Role['Administrator']:
            return response_error("Access deny!")

        return f(*args, **kwargs)
Example #13
0
def remove(id):
    try:
        uid = int(request.headers['Uid'])
        cate = db.session.query(Category).filter(
            and_(Category.id == id, Category.created_user_id == uid)).first()
        if cate is not None:
            db.session.delete(cate)
            db.session.commit()
            return response_ok(message="{} has been deleted!".format(cate.id))
        else:
            return response_error(MESSAGE.INVALID_DATA, CODE.INVALID_DATA)

    except Exception, ex:
        db.session.rollback()
        return response_error(ex.message)
Example #14
0
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)
Example #15
0
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)
def handshakes():
	uid = int(request.headers['Uid'])
	try:
		data = request.json
		if data is None:
			return response_error(MESSAGE.INVALID_DATA, CODE.INVALID_DATA)

		outcome_id = data.get('outcome_id', -1)
		outcome = Outcome.find_outcome_by_id(outcome_id)
		if outcome is None:
			return response_error(MESSAGE.INVALID_BET, CODE.INVALID_BET)
		
		match = Match.find_match_by_id(outcome.match_id)
		supports = handshake_bl.find_available_support_handshakes(outcome_id)
		againsts = handshake_bl.find_available_against_handshakes(outcome_id)

		total = Decimal('0', 2)

		traded_volumns = db.session.query(func.sum(Handshake.amount*Handshake.odds).label('traded_volumn')).filter(and_(Handshake.outcome_id==outcome_id, Handshake.status==CONST.Handshake['STATUS_INITED'])).group_by(Handshake.odds).all()
		for traded in traded_volumns:
			total += traded[0]

		arr_supports = []
		for support in supports:
			data = {}
			data['odds'] = support.odds
			data['amount'] = support.amount
			arr_supports.append(data)

		arr_against = []
		for against in againsts:
			data = {}
			data['odds'] = against.odds
			data['amount'] = against.amount
			arr_against.append(data)

		response = {
			"support": arr_supports,
			"against": arr_against,
			"traded_volumn": total,
			"market_fee": match.market_fee
		}

		return response_ok(response)

	except Exception, ex:
		return response_error(ex.message)
def remove(outcome_id):
    try:
        uid = int(request.headers['Uid'])
        outcome = db.session.query(Outcome).filter(
            and_(Outcome.id == outcome_id,
                 Outcome.created_user_id == uid)).first()
        if outcome is not None:
            db.session.delete(outcome)
            db.session.commit()
            return response_ok("{} has been deleted!".format(outcome.id))
        else:
            return response_error(MESSAGE.OUTCOME_INVALID,
                                  CODE.OUTCOME_INVALID)

    except Exception, ex:
        db.session.rollback()
        return response_error(ex.message)
Example #18
0
def add_type():
    try:
        data = request.json
        if data is None:
            return response_error(MESSAGE.INVALID_DATA, CODE.INVALID_DATA)

        for d in data:
            if 'name' in d:
                r = ReviewType(name=d['name'].lower())
                db.session.add(r)
                db.session.flush()

        db.session.commit()
        return response_ok()
    except Exception, ex:
        db.session.rollback()
        return response_error(ex.message)
Example #19
0
def init_default_odds():
	"""
	"	Admin create odds for market in ETH
	"""
	try:
		data = request.json
		if data is None:
			return response_error(MESSAGE.INVALID_DATA, CODE.INVALID_DATA)

		for item in data:
			outcome_id = item['outcome_id']
			outcome_data = item['outcomes']
			outcome = Outcome.find_outcome_by_id(outcome_id)
			if outcome is None:
				return response_error(MESSAGE.OUTCOME_INVALID, CODE.OUTCOME_INVALID)

			if outcome.result != CONST.RESULT_TYPE['PENDING']:
				return response_error(MESSAGE.OUTCOME_HAS_RESULT, CODE.OUTCOME_HAS_RESULT)

			match = Match.find_match_by_id(outcome.match_id)
			for o in outcome_data:
				o['outcome_id'] = outcome_id
				o['hid'] = outcome.hid
				o['match_date'] = match.date
				o['match_name'] = match.name
				o['outcome_name'] = outcome.name

				contract = Contract.find_contract_by_id(outcome.contract_id)
				if contract is None:
					return response_error(MESSAGE.CONTRACT_INVALID, CODE.CONTRACT_INVALID)

				task = Task(
					task_type=CONST.TASK_TYPE['REAL_BET'],
					data=json.dumps(o),
					action=CONST.TASK_ACTION['INIT'],
					status=-1,
					contract_address=contract.contract_address,
					contract_json=contract.json_name
				)
				db.session.add(task)
				db.session.flush()
		
		return response_ok()
	except Exception, ex:
		db.session.rollback()
		return response_error(ex.message)
Example #20
0
def user_accept_notification():
    """
	" user input their email in notification section on create market page.
	"""
    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)

        is_need_send_verification_code = data.get(
            'need_send_verification_code', 0)
        email = data["email"]
        is_subscribed = user_bl.is_email_subscribed(email)

        if is_need_send_verification_code == 1:
            if is_subscribed == False:
                return response_error(
                    MESSAGE.USER_CANNOT_RECEIVE_VERIFICATION_CODE,
                    CODE.USER_CANNOT_RECEIVE_VERIFICATION_CODE)

        elif is_subscribed:
            return response_error(MESSAGE.EMAIL_ALREADY_SUBSCRIBED,
                                  CODE.EMAIL_ALREADY_SUBSCRIBED)

        uid = int(request.headers["Uid"])
        user = User.find_user_with_id(uid)
        user.email = email
        user.is_subscribe = 1
        user.is_user_disable_popup = 0
        db.session.flush()

        # send email
        subscribe_notification_email.delay(email, request.headers["Fcm-Token"],
                                           request.headers["Payload"], uid)

        db.session.commit()
        return response_ok()

    except Exception, ex:
        db.session.rollback()
        return response_error(ex.message)
Example #21
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)
Example #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)
Example #23
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)
Example #24
0
def approve_source(source_id):
	try:
		source = Source.find_source_by_id(source_id)
		if source is not None:
			if source.approved != 1:
				source.approved = 1
				db.session.flush()
			else:
				return response_error(MESSAGE.SOURCE_APPOVED_ALREADY, CODE.SOURCE_APPOVED_ALREADY)
				
		else:
			return response_error(MESSAGE.SOURCE_INVALID, CODE.SOURCE_INVALID)

		db.session.commit()
		return response_ok(source.to_json())
	except Exception, ex:
		db.session.rollback()
		return response_error(ex.message)
Example #25
0
def delete_answer():
	try:
		comment_id = request.args.get('id', -1)
		if comment_id == -1:
			return response_error(MESSAGE.ANSWER_INVALID_INPUT, CODE.ANSWER_INVALID_INPUT)

		review = answer_bl.review_type(comment_id)
		if review is None:
			return response_error(MESSAGE.ANSWER_INVALID_INPUT, CODE.ANSWER_INVALID_INPUT)

		comment = db.session.query(Comment).filter(Comment.id==comment_id).first()
		rating = db.session.query(Rating).filter(Rating.id.in_(db.session.query(Comment.rating_id).filter(Comment.id==comment_id))).first()

		db.session.delete(comment)
		db.session.delete(rating)
	
		object_id = rating.object_id
		review_type = review.name
		if review_type == CONST.Type['People']:
			user = User.find_user_by_id(object_id)
			if user is not None:
				user.rating_count = people_bl.count_rating_for_object(user, CONST.Type['People'])
				user.comment_count = people_bl.count_comments_for_object(user, CONST.Type['People'])
				db.session.flush()

		elif review_type == CONST.Type['Team']:
			team = Team.find_team_by_id(object_id)
			if team is not None:
				team.rating_count = people_bl.count_rating_for_object(team, CONST.Type['Team'])
				team.comment_count = people_bl.count_comments_for_object(team, CONST.Type['Team'])
				db.session.flush()

		elif review_type == CONST.Type['Company']:
			company = Company.find_company_by_id(object_id)
			if company is not None:
				company.rating_count = people_bl.count_rating_for_object(company, CONST.Type['Company'])
				company.comment_count = people_bl.count_comments_for_object(company, CONST.Type['Company'])
				db.session.flush()

		db.session.commit()
		return response_ok()
	except Exception, ex:
		db.session.rollback()
		return response_error(ex.message)
Example #26
0
def event():
    try:
        data = request.json
        print 'event = {}'.format(data)
        if data is None:
            return response_error(MESSAGE.INVALID_DATA, CODE.INVALID_DATA)

        status = data.get('status', 1)
        tx_id = int(data['id'])

        handshakes = []
        shakers = []
        tx = Tx.find_tx_by_id(tx_id)
        event_name = ''
        if status == 1:
            event_name = data['eventName']
            inputs = data['inputs']
            handshakes, shakers = handshake_bl.save_handshake_for_event(
                event_name, inputs)

        elif status == 0:
            method = data.get('methodName', '')
            inputs = data['inputs']
            handshakes, shakers = handshake_bl.save_handshake_method_for_event(
                method, inputs)

        elif status == 2:
            method = data.get('methodName', '')
            handshakes, shakers = handshake_bl.save_failed_handshake_method_for_event(
                method, tx)

        if tx is not None:
            tx.status = status
            db.session.flush()

        db.session.commit()

        handshake_bl.update_handshakes_feed(handshakes, shakers)
        event_bl.run_bots_for_tx(tx)

        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)
Example #28
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)
Example #29
0
    def wrap(*args, **kwargs):
        remote = request.remote_addr
        route = list(request.access_route)
        while remote not in trusted_proxies:
            remote = route.pop()

        if remote not in white_ips:
            return response_error("Access deny!")

        return f(*args, **kwargs)
Example #30
0
def update_feed_status():
	try:
		data = request.json
		is_maker = int(data.get('is_maker', -1))
		item_id = int(data.get('id', -1))
		status = int(data.get('status', -1))
		amount = data.get('amount') # string
		remaining_amount = data.get('remaining_amount') # string

		if is_maker == -1 or status == -1 or item_id == -1:
			return response_error(MESSAGE.INVALID_DATA, CODE.INVALID_DATA)

		handshake = None

		if is_maker == 1:
			handshake = Handshake.find_handshake_by_id(item_id)
			if handshake is not None:
				handshake.status = status
				if amount is not None:
					handshake.amount = amount
				if remaining_amount is not None:
					handshake.remaining_amount = remaining_amount
		else:
			shaker = Shaker.find_shaker_by_id(item_id)
			if shaker is not None:
				shaker.status = status
				handshake = Handshake.find_handshake_by_id(shaker.handshake_id)
				if handshake is not None:
					status = handshake.status

					if amount is not None:
						handshake.amount = amount
					if remaining_amount is not None:
						handshake.remaining_amount = remaining_amount

		db.session.flush()
		db.session.commit()
		update_status_feed.delay(handshake.id, status, amount=amount, remaining_amount=remaining_amount)
		return response_ok()

	except Exception, ex:
		db.session.rollback()
		return response_error(ex.message)