def test_hook_update_comment_count(self): t = datetime.now().timetuple() seconds = local_to_utc(t) match = Match.find_match_by_id(4685) if match is not None: match.date = seconds + 100 match.reportTime = seconds + 200 match.disputeTime = seconds + 300 match.source_id = 3 else: match = Match(id=4685, public=1, date=seconds + 100, reportTime=seconds + 200, disputeTime=seconds + 300, source_id=3) db.session.add(match) db.session.commit() # Test email is null with self.client: params = {"commentNumber": 8, "objectId": 'outcome_id_4685'} response = self.client.post('/hook/comment-count', data=json.dumps(params), content_type='application/json') data = json.loads(response.data.decode()) self.assertTrue(data['status'] == 1)
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)
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 test_add_outcome(self): t = datetime.now().timetuple() seconds = local_to_utc(t) arr_match = [] Uid = 66 source1 = Source.find_source_by_id(1) if source1 is None: source1 = Source(id=1, name="Source", url="htpp://www.abc.com", approved=1) db.session.add(source1) db.session.commit() match = Match(public=1, date=seconds + 100, reportTime=seconds + 200, disputeTime=seconds + 300, source_id=source1.id) arr_match.append(match) db.session.add(match) db.session.commit() with self.client: params = [{ "name": "outcome test", "match_id": match.id, "hid": 88 }] response = self.client.post('/outcome/add/{}'.format(match.id), data=json.dumps(params), content_type='application/json', headers={ "Uid": "{}".format(Uid), "Fcm-Token": "{}".format(123), "Payload": "{}".format(123), }) data = json.loads(response.data.decode()) self.assertTrue(data['status'] == 1) data_json = data['data'] self.assertTrue( data_json[0]['approved'] == CONST.OUTCOME_STATUS['PENDING']) response = self.client.get('/match/{}'.format(match.id), content_type='application/json', headers={ "Uid": "{}".format(Uid), "Fcm-Token": "{}".format(123), "Payload": "{}".format(123), }) data = json.loads(response.data.decode()) self.assertTrue(data['status'] == 1) data_json = data['data'] self.assertTrue(len(data_json['outcomes']) == 0) for item in arr_match: db.session.delete(item) db.session.commit()
def test_report_match(self): self.clear_data_before_test() t = datetime.now().timetuple() seconds = local_to_utc(t) match = Match.find_match_by_id(1) if match is not None: match.date = seconds - 1000 match.reportTime = seconds + 1000 match.disputeTime = seconds + 2000 with self.client: response = self.client.post( 'admin/match/report/1', headers={ "Authorization": "Bearer {}".format( create_access_token(identity=app.config.get("EMAIL"), fresh=True)), "Uid": "{}".format(1000), "Fcm-Token": "{}".format(123), "Payload": "{}".format(123), }) data = json.loads(response.data.decode()) self.assertTrue(data['status'] == 0)
def is_exceed_closing_time(match_id): match = Match.find_match_by_id(match_id) if match.date is not None: t = datetime.now().timetuple() seconds = local_to_utc(t) if seconds > match.date: return True return False
def test_get_list_match_resolve_by_admin(self): self.clear_data_before_test() arr_hs = [] t = datetime.now().timetuple() seconds = local_to_utc(t) # ----- match2 = Match(date=seconds - 200, reportTime=seconds - 100, disputeTime=seconds + 300, created_user_id=88, name="Dispute") db.session.add(match2) db.session.commit() # ----- outcome1 = Outcome(match_id=match2.id, hid=1, result=CONST.RESULT_TYPE['DISPUTED'], contract_id=1) db.session.add(outcome1) db.session.commit() with self.client: response = self.client.get( 'admin/match/resolve', headers={ "Authorization": "Bearer {}".format( create_access_token(identity=app.config.get("EMAIL"), fresh=True)), "Uid": "{}".format(88), "Fcm-Token": "{}".format(123), "Payload": "{}".format(123), }) data = json.loads(response.data.decode()) self.assertTrue(data['status'] == 1) data_json = data['data'] tmp = None for m in data_json: if m['id'] == match2.id: tmp = m break self.assertNotEqual(tmp, None)
def is_validate_match_time(data): if 'date' not in data or 'reportTime' not in data or 'disputeTime' not in data: return False t = datetime.now().timetuple() seconds = local_to_utc(t) if seconds >= data['date'] or seconds >= data[ 'reportTime'] or seconds >= data['disputeTime']: return False if data['date'] < data['reportTime'] and data['reportTime'] < data[ 'disputeTime']: return True return False
def get_text_list_need_approve(): t = datetime.now().timetuple() seconds = local_to_utc(t) text = "" matches = db.session.query(Match)\ .filter(\ Match.deleted == 0,\ Match.date > seconds,\ Match.id.in_(db.session.query(Outcome.match_id).filter(and_(Outcome.result == -1, Outcome.hid == None, Outcome.approved == CONST.OUTCOME_STATUS['PENDING'])).group_by(Outcome.match_id)) )\ .all() print matches for match in matches: text += '[{}] {} - match id: {}, closing time: {}\n'.format( app.config['ENV'], match.name, match.id, second_to_strftime(match.date, is_gmt=True)) return text
def get_text_list_need_approve(self): t = datetime.now().timetuple() seconds = local_to_utc(t) items = [] match = Match(public=1, date=seconds - 100, reportTime=seconds + 200, disputeTime=seconds + 300, source_id=3) db.session.add(match) db.session.commit() items.append(match) outcome = Outcome(match_id=match.id, name="test approve", approved=-1) db.session.add(outcome) items.append(outcome) db.session.commit() match1 = Match(public=0, date=seconds - 100, reportTime=seconds + 200, disputeTime=seconds + 300, source_id=3) db.session.add(match1) db.session.commit() items.append(match1) outcome1 = Outcome(match_id=match1.id, name="test approve", approved=-1) db.session.add(outcome1) db.session.commit() items.append(outcome1) text = match_bl.get_text_list_need_approve() for item in items: db.session.delete(item) db.session.commit() self.assertTrue(text != '')
def count_events_based_on_source(): """ " This is used for extension in order to show badge. """ try: source = request.args.get('source') code = request.args.get('code') if source is None: return response_error() server_key = hashlib.md5('{}{}'.format(source, g.PASSPHASE)).hexdigest() if server_key != code: return response_error() response = {"bets": 0} url = match_bl.clean_source_with_valid_format(source) t = datetime.now().timetuple() seconds = local_to_utc(t) match = db.session.query(Match)\ .filter(\ Match.deleted == 0,\ Match.date > seconds,\ Match.source_id.in_(db.session.query(Source.id).filter(Source.url.contains(url))),\ Match.id.in_(db.session.query(Outcome.match_id).filter(and_(Outcome.result == -1)).group_by(Outcome.match_id)))\ .all() if match is None: return response_error(MESSAGE.MATCH_NOT_FOUND, CODE.MATCH_NOT_FOUND) response["bets"] = len(match) return response_ok(response) except Exception, ex: return response_error(ex.message)
def match_need_user_report(): try: uid = int(request.headers['Uid']) t = datetime.now().timetuple() seconds = local_to_utc(t) response = [] contracts = contract_bl.all_contracts() # Get all matchs are PENDING (-1) matches = db.session.query(Match).filter( and_( Match.date < seconds, Match.reportTime >= seconds, Match.id.in_( db.session.query(Outcome.match_id).filter( and_(Outcome.result == CONST.RESULT_TYPE['PENDING'], Outcome.hid != None, Outcome.created_user_id == uid)).group_by( Outcome.match_id)))).all() # Filter all outcome of user for match in matches: match_json = match.to_json() arr_outcomes = [] for outcome in match.outcomes: if outcome.created_user_id == uid and outcome.hid >= 0 and outcome.approved == 1: outcome_json = contract_bl.filter_contract_id_in_contracts( outcome.to_json(), contracts) arr_outcomes.append(outcome_json) match_json["outcomes"] = arr_outcomes response.append(match_json) return response_ok(response) except Exception, ex: return response_error(ex.message)
def test_is_validate_match_time(self): t = datetime.now().timetuple() seconds = local_to_utc(t) data = { "date": seconds, "reportTime": seconds + 1000, "disputeTime": seconds + 2000 } expected = False actual = match_bl.is_validate_match_time(data) self.assertEqual(actual, expected) # ------- data = { "date": seconds + 1000, "reportTime": seconds + 1000, "disputeTime": seconds + 2000 } expected = False actual = match_bl.is_validate_match_time(data) self.assertEqual(actual, expected) # ------- data = { "date": seconds + 1000, "reportTime": seconds + 2000, "disputeTime": seconds + 3000 } expected = True actual = match_bl.is_validate_match_time(data) self.assertEqual(actual, expected)
def test_can_refund_for_maker(self): self.clear_data_before_test() t = datetime.now().timetuple() seconds = local_to_utc(t) match = Match.find_match_by_id(1) match.disputeTime = seconds + 1100 match.reportTime = seconds + 1000 db.session.merge(match) db.session.commit() arr_hs = [] # ----- handshake = Handshake( hs_type=3, chain_id=4, user_id=88, outcome_id=88, odds=1.5, amount=1, currency='ETH', side=2, remaining_amount=0, from_address='0x123', status=0 ) db.session.add(handshake) db.session.commit() arr_hs.append(handshake) actual = handshake_bl.can_refund(handshake) expected = False self.assertEqual(actual, expected) # test cannot refund outcome = Outcome.find_outcome_by_id(88) outcome.result = 1 db.session.merge(outcome) db.session.flush() actual = handshake_bl.can_refund(handshake) expected = False self.assertEqual(actual, expected) # test refund if time exceed report time outcome.result = -1 db.session.merge(outcome) db.session.flush() match.reportTime = seconds - 2000 db.session.merge(match) db.session.commit() actual = handshake_bl.can_refund(handshake) expected = True self.assertEqual(actual, expected) for item in arr_hs: db.session.delete(item) db.session.commit()
def search(self, text): t = datetime.now().timetuple() seconds = local_to_utc(t) return self.index.search( text, {"filters": "closingTime > {}".format(seconds)})
def update_image(source_id): try: source = Source.find_source_by_id(source_id) if source is None: return False request_size = request.headers.get('Content-length') # string is_update_matchs = request.form.get('update_matchs', '0') == '1' image_name = '{}_{}'.format(source.id, source.name).lower() image_name = re.sub(r'[^A-Za-z0-9\_\-\.]+', '_', image_name) image_name = '{}.jpg'.format(image_name) if request.files and len( request.files) > 0 and request.files['image'] is not None: if int( request_size ) <= CONST.UPLOAD_MAX_FILE_SIZE and storage_bl.validate_extension( request.files['image'].filename, CONST.UPLOAD_ALLOWED_EXTENSIONS): image_name, saved_path = storage_bl.handle_upload_file( request.files['image'], file_name=image_name) saved_path, crop_saved_path = storage_bl.handle_crop_image( image_name, saved_path) else: return response_error(MESSAGE.FILE_TOO_LARGE, CODE.FILE_TOO_LARGE) if image_name is not None and saved_path is not None: result_upload = gc_storage_client.upload_to_storage( app.config.get('GC_STORAGE_BUCKET'), crop_saved_path, '{}/{}'.format(app.config.get('GC_STORAGE_FOLDER'), app.config.get('GC_DEFAULT_FOLDER')), image_name, True) if result_upload is False: return response_error() storage_bl.delete_file(crop_saved_path) storage_bl.delete_file(saved_path) # Update image_url all matchs if is_update_matchs: t = datetime.now().timetuple() seconds = local_to_utc(t) matches = db.session.query(Match)\ .filter(\ and_(\ Match.source_id == source.id, or_(Match.image_url == None, Match.image_url == ""), Match.deleted == 0,\ Match.date > seconds,\ Match.public == 1,\ Match.id.in_(db.session.query(Outcome.match_id).filter(and_(Outcome.result == -1, Outcome.hid != None)).group_by(Outcome.match_id)) )\ )\ .all() image_url = CONST.SOURCE_GC_DOMAIN.format( app.config['GC_STORAGE_BUCKET'], '{}/{}'.format(app.config.get('GC_STORAGE_FOLDER'), app.config.get('GC_DEFAULT_FOLDER')), image_name) for match in matches: match.image_url = image_url db.session.flush() db.session.commit() return response_ok() except Exception, ex: db.session.rollback() return response_error(ex.message)
def report_match(match_id): """ Report match by match_id: "" If report is 'PROCESSING' status, tnx's action is 'REPORT' "" If report is 'DISPUTED' status, tnx's action is 'RESOLVE' "" "" Input: "" match_id """ try: t = datetime.now().timetuple() seconds = local_to_utc(t) data = request.json if data is None: return response_error(MESSAGE.INVALID_DATA, CODE.INVALID_DATA) match = db.session.query(Match).filter(\ Match.date < seconds, Match.id == match_id).first() if match is not None: result = data['result'] if result is None: return response_error(MESSAGE.MATCH_RESULT_EMPTY) disputed = False for item in result: if 'side' not in item: return response_error(MESSAGE.OUTCOME_INVALID_RESULT) if 'outcome_id' not in item: return response_error(MESSAGE.OUTCOME_INVALID) outcome = db.session.query(Outcome).filter(Outcome.id==item['outcome_id'], Outcome.match_id==match.id).first() if outcome is not None: 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 if outcome.result == CONST.RESULT_TYPE['DISPUTED']: disputed = True outcome.result = CONST.RESULT_TYPE['PROCESSING'] else: return response_error(MESSAGE.OUTCOME_INVALID) contract = Contract.find_contract_by_id(outcome.contract_id) if contract is None: return response_error(MESSAGE.CONTRACT_INVALID, CODE.CONTRACT_INVALID) report = {} report['offchain'] = CONST.CRYPTOSIGN_OFFCHAIN_PREFIX + ('resolve' if disputed else 'report') + str(outcome.id) + '_' + str(item['side']) report['hid'] = outcome.hid report['outcome_id'] = outcome.id report['outcome_result'] = item['side'] report['creator_wallet_address'] = match.creator_wallet_address report['grant_permission'] = match.grant_permission task = Task( task_type=CONST.TASK_TYPE['REAL_BET'], data=json.dumps(report), action=CONST.TASK_ACTION['RESOLVE' if disputed else 'REPORT'], status=-1, contract_address=contract.contract_address, contract_json=contract.json_name ) db.session.add(task) db.session.flush() db.session.commit() return response_ok(match.to_json()) else: return response_error(MESSAGE.MATCH_NOT_FOUND, CODE.MATCH_NOT_FOUND) except Exception, ex: db.session.rollback() return response_error(ex.message)
def test_hook_slack_command(self): t = datetime.now().timetuple() seconds = local_to_utc(t) match = Match.find_match_by_id(4685) if match is not None: for o in match.outcomes: db.session.delete(o) db.session.commit() db.session.delete(match) db.session.commit() match = Match(id=4685, public=1, date=seconds + 100, reportTime=seconds + 200, disputeTime=seconds + 300, source_id=3) db.session.add(match) db.session.commit() outcome = Outcome(match_id=match.id, name="test approve", approved=CONST.OUTCOME_STATUS['PENDING']) db.session.add(outcome) db.session.commit() with self.client: url_query_str = """token=ABC123&team_id=T0001&team_domain=example&channel_id=C123456&channel_name=test&user_id=U123456&user_name=Steve&command=%2Fweather&text={}_{}&response_url=https://hooks.slack.com/commands/1234/5678""".format( match.id, 1) response = self.client.get( '/hook/slack/command?{}'.format(url_query_str)) data = json.loads(response.data.decode()) self.assertTrue(data['status'] == 1) # Case: outcome was approved or rejected match = Match.find_match_by_id(4685) if match is not None: for o in match.outcomes: db.session.delete(o) db.session.commit() db.session.delete(match) db.session.commit() match = Match(id=4685, public=1, date=seconds + 100, reportTime=seconds + 200, disputeTime=seconds + 300, source_id=3) db.session.add(match) db.session.commit() outcome = Outcome( match_id=match.id, name="test approve", # hid=1 approved=CONST.OUTCOME_STATUS['APPROVED']) db.session.add(outcome) db.session.commit() with self.client: url_query_str = """token=ABC123&team_id=T0001&team_domain=example&channel_id=C123456&channel_name=test&user_id=U123456&user_name=Steve&command=%2Fweather&text={}_{}&response_url=https://hooks.slack.com/commands/1234/5678""".format( match.id, 1) response = self.client.get( '/hook/slack/command?{}'.format(url_query_str)) data = json.loads(response.data.decode()) self.assertTrue(data['status'] != 1) # Case: time invalid match = Match.find_match_by_id(4685) if match is not None: for o in match.outcomes: db.session.delete(o) db.session.commit() db.session.delete(match) db.session.commit() match = Match(id=4685, public=1, date=seconds - 100, reportTime=seconds + 200, disputeTime=seconds + 300, source_id=3) db.session.add(match) db.session.commit() outcome = Outcome( match_id=match.id, name="test approve", # hid=1 approved=CONST.OUTCOME_STATUS['APPROVED']) db.session.add(outcome) db.session.commit() with self.client: url_query_str = """token=ABC123&team_id=T0001&team_domain=example&channel_id=C123456&channel_name=test&user_id=U123456&user_name=Steve&command=%2Fweather&text={}_{}&response_url=https://hooks.slack.com/commands/1234/5678""".format( match.id, 1) response = self.client.get( '/hook/slack/command?{}'.format(url_query_str)) data = json.loads(response.data.decode()) self.assertTrue(data['status'] == 0) for o in match.outcomes: db.session.delete(o) db.session.commit() db.session.delete(match) db.session.commit()
def test_hook_slack_command1(self): t = datetime.now().timetuple() seconds = local_to_utc(t) items = [] match = Match(name='DDDDD', public=1, date=seconds - 100, reportTime=seconds + 200, disputeTime=seconds + 300, source_id=3) db.session.add(match) db.session.commit() items.append(match) outcome = Outcome(match_id=match.id, name="test approve", result=-1, approved=-1) db.session.add(outcome) items.append(outcome) db.session.commit() match1 = Match(name='BBBBB', public=0, date=seconds - 100, reportTime=seconds + 200, disputeTime=seconds + 300, source_id=3) db.session.add(match1) db.session.commit() items.append(match1) outcome1 = Outcome(match_id=match1.id, name="test approve", result=-1, approved=-1) db.session.add(outcome1) db.session.commit() items.append(outcome1) match2 = Match(name='AAAAAAA', public=0, date=seconds - 100, reportTime=seconds + 200, disputeTime=seconds + 300, source_id=3) db.session.add(match2) db.session.commit() items.append(match2) outcome2 = Outcome(match_id=match2.id, name="test approve", result=-1, approved=0) db.session.add(outcome2) db.session.commit() items.append(outcome2) text = match_bl.get_text_list_need_approve() for item in items: db.session.delete(item) db.session.commit() self.assertTrue(text != '')
def test_get_match_created_user(self): arr_remove = [] t = datetime.now().timetuple() seconds = local_to_utc(t) user_id = 8888 user = User.find_user_with_id(user_id) if user is None: user = User( id=user_id ) db.session.add(user) db.session.commit() arr_remove.append(user) matches = db.session.query(Match)\ .filter(\ Match.created_user_id == user_id,\ Match.id.in_(db.session.query(Outcome.match_id).filter(Outcome.hid != None).group_by(Outcome.match_id)))\ .order_by(Match.date.asc(), Match.index.desc())\ .all() for item in matches: db.session.delete(item) db.session.commit() with self.client: # Add match is not expire match1 = Match.find_match_by_id(1000) if match1 is not None: match1.created_user_id = user_id match1.date=seconds - 100, match1.reportTime=seconds + 100, match1.disputeTime=seconds + 200, match1.public=1 db.session.flush() else: match1 = Match( id=1000, created_user_id = user_id, date=seconds - 100, reportTime=seconds + 100, disputeTime=seconds + 200, public=1 ) db.session.add(match1) db.session.commit() outcome1 = Outcome( match_id=1000, hid=0 ) db.session.add(outcome1) db.session.commit() arr_remove.append(match1) arr_remove.append(outcome1) # ----- # Add match expired match2 = Match.find_match_by_id(1001) if match2 is not None: match2.created_user_id = user_id match2.date=seconds + 100, match2.reportTime=seconds + 200, match2.disputeTime=seconds + 300, match2.public = 1 db.session.flush() else: match2 = Match( id=1001, created_user_id = user_id, date=seconds + 100, reportTime=seconds + 200, disputeTime=seconds + 300, public=1 ) db.session.add(match2) outcome2 = Outcome( match_id=1001, hid=0 ) db.session.add(outcome2) db.session.commit() arr_remove.append(match2) arr_remove.append(outcome2) # Add match has result match3 = Match.find_match_by_id(1002) if match3 is not None: match3.created_user_id = user_id match3.date=seconds + 100, match3.reportTime=seconds + 200, match3.disputeTime=seconds + 300, match3.public = 1 db.session.flush() else: match3 = Match( id=1002, created_user_id = user_id, date=seconds + 100, reportTime=seconds + 200, disputeTime=seconds + 300, public=1 ) db.session.add(match3) outcome3 = Outcome( match_id=1002, hid=0, result=1 ) db.session.add(outcome3) db.session.commit() arr_remove.append(match3) arr_remove.append(outcome3) # ----- # call match endpoint again response = self.client.get( '/reputation/{}'.format(user_id), headers={ "Uid": "{}".format(user_id), "Fcm-Token": "{}".format(123), "Payload": "{}".format(123), }) data = json.loads(response.data.decode()) self.assertTrue(data['status'] == 1) self.assertTrue(len(data['data']['matches']) == 3) for item in arr_remove: db.session.delete(item) db.session.commit()
def match_detail(match_id): """ " This endpoint will be called when user shares link to his/her friends """ try: outcome_id = int(request.args.get('outcome_id', -1)) t = datetime.now().timetuple() seconds = local_to_utc(t) match = db.session.query(Match)\ .filter(\ Match.id == match_id,\ Match.deleted == 0,\ Match.date > seconds,\ Match.id.in_(db.session.query(Outcome.match_id).filter(and_(Outcome.result == -1, Outcome.hid > 0)).group_by(Outcome.match_id)))\ .first() if match is None: return response_error(MESSAGE.MATCH_NOT_FOUND, CODE.MATCH_NOT_FOUND) arr_outcomes = outcome_bl.check_outcome_valid(match.outcomes) if len(arr_outcomes) > 0: match_json = match.to_json() if match.source is not None: source_json = match_bl.handle_source_data(match.source) match_json["source"] = source_json if match.category is not None: match_json["category"] = match.category.to_json() match_json["outcomes"] = arr_outcomes total_users, total_bets = match_bl.get_total_user_and_amount_by_match_id( match.id) if total_users == 0 and total_bets == 0: total_users, total_bets = match_bl.fake_users_and_bets() support_users, oppose_users = match_bl.fake_support_and_oppose_users( total_users) match_json["total_users"] = total_users match_json["total_bets"] = total_bets match_json["bets_side"] = { "support": support_users, "oppose": oppose_users } else: match_json["total_users"] = total_users match_json["total_bets"] = total_bets match_json["bets_side"] = { "support": outcome_bl.count_support_users_play_on_outcome( match.outcomes[0].id), "oppose": outcome_bl.count_against_users_play_on_outcome( match.outcomes[0].id) } return response_ok(match_json) return response_error(MESSAGE.OUTCOME_INVALID, CODE.OUTCOME_INVALID) except Exception, ex: return response_error(ex.message)
def matches(): try: uid = int(request.headers['Uid']) source = request.args.get('source') keywords = request.args.get('keywords') response = [] matches = [] t = datetime.now().timetuple() seconds = local_to_utc(t) matches = db.session.query(Match)\ .filter(\ Match.deleted == 0,\ Match.date > seconds,\ Match.public == 1,\ 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() # get suggested matches from recombee match_ids_recommended = match_bl.get_user_recommended_data( user_id=uid, offset=20, timestamp=seconds) # get suggested matches from algolia arr_ids = match_bl.algolia_search(source, keywords) if arr_ids is not None and len(arr_ids) > 0: match_ids_recommended.extend(arr_ids) # sort them if len(match_ids_recommended) > 0: matches = sorted(matches, key=lambda m: m.id not in match_ids_recommended) for match in matches: arr_outcomes = outcome_bl.check_outcome_valid(match.outcomes) if len(arr_outcomes) > 0: match_json = match.to_json() if match.source is not None: source_json = match_bl.handle_source_data(match.source) match_json["source"] = source_json if match.category is not None: match_json["category"] = match.category.to_json() match_json["outcomes"] = arr_outcomes total_users, total_bets = match_bl.get_total_user_and_amount_by_match_id( match.id) if total_users == 0 and total_bets == 0: total_users, total_bets = match_bl.fake_users_and_bets() support_users, oppose_users = match_bl.fake_support_and_oppose_users( total_users) match_json["total_users"] = total_users match_json["total_bets"] = total_bets match_json["bets_side"] = { "support": support_users, "oppose": oppose_users } else: match_json["total_users"] = total_users match_json["total_bets"] = total_bets match_json["bets_side"] = { "support": outcome_bl.count_support_users_play_on_outcome( match.outcomes[0].id), "oppose": outcome_bl.count_against_users_play_on_outcome( match.outcomes[0].id) } response.append(match_json) return response_ok(response) except Exception, ex: return response_error(ex.message)
def test_can_withdraw(self): self.clear_data_before_test() match = Match.find_match_by_id(1) t = datetime.now().timetuple() seconds = local_to_utc(t) if match is None: match = Match( public=1, date=seconds - 100, reportTime=seconds + 200, disputeTime=seconds + 300, source_id = source.id ) db.session.add(match) db.session.commit() else: match.date = time.time() - 100 match.disputeTime = time.time() + 200 match.reportTime = time.time() + 300 db.session.commit() outcome = Outcome.find_outcome_by_id(88) if outcome is not None: outcome.result = 1 outcome.match_id=match.id else: outcome = Outcome( id=88, match_id=match.id, result=1, hid=88, contract_id=1 ) db.session.add(outcome) db.session.commit() actual = handshake_bl.can_withdraw(None, shaker=None) self.assertNotEqual(len(actual), 0) # ----- handshake = Handshake( hs_type=3, chain_id=4, user_id=88, outcome_id=9999999, odds=1.2, amount=1, currency='ETH', side=1, remaining_amount=0, from_address='0x123', status=0 ) actual = handshake_bl.can_withdraw(handshake, shaker=None) self.assertEqual(actual, MESSAGE.OUTCOME_INVALID) # ----- handshake = Handshake( hs_type=3, chain_id=4, user_id=88, outcome_id=88, odds=1.2, amount=1, currency='ETH', side=2, remaining_amount=0, from_address='0x123', status=0 ) actual = handshake_bl.can_withdraw(handshake, shaker=None) self.assertEqual(actual, MESSAGE.HANDSHAKE_NOT_THE_SAME_RESULT) # ----- handshake = Handshake( hs_type=3, chain_id=4, user_id=88, outcome_id=88, odds=1.2, amount=1, currency='ETH', side=1, remaining_amount=0, from_address='0x123', status=0 ) actual = handshake_bl.can_withdraw(handshake, shaker=None) self.assertEqual(actual, MESSAGE.HANDSHAKE_WITHDRAW_AFTER_DISPUTE) match = Match.find_match_by_id(1) match.disputeTime = time.time() - 1000 match.reportTime = time.time() - 1000 db.session.commit() # ----- handshake = Handshake( hs_type=3, chain_id=4, user_id=88, outcome_id=88, odds=1.2, amount=1, currency='ETH', side=1, remaining_amount=0, from_address='0x123', status=0 ) actual = handshake_bl.can_withdraw(handshake, shaker=None) self.assertEqual(actual, '')
def relevant_events(): try: match_id = int(request.args.get('match')) if request.args.get( 'match') is not None else None match = Match.find_match_by_id(match_id) response = [] matches = [] t = datetime.now().timetuple() seconds = local_to_utc(t) if match is None: return response_error(MESSAGE.INVALID_DATA, CODE.INVALID_DATA) matches = db.session.query(Match)\ .filter(\ or_(Match.source_id == match.source_id, Match.category_id == match.category_id),\ Match.deleted == 0,\ Match.date > seconds,\ Match.public == 1,\ Match.id != match_id, \ 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() # Get all source_id source_ids = list( OrderedDict.fromkeys(list(map(lambda x: x.source_id, matches)))) sources = db.session.query(Source)\ .filter(\ Source.id.in_(source_ids))\ .all() for match in matches: match_json = match.to_json() arr_outcomes = outcome_bl.check_outcome_valid(match.outcomes) if len(arr_outcomes) > 0: match_json = match.to_json() if match.source is not None: source_json = match_bl.handle_source_data(match.source) match_json["source"] = source_json if match.category is not None: match_json["category"] = match.category.to_json() match_json["outcomes"] = arr_outcomes total_users, total_bets = match_bl.get_total_user_and_amount_by_match_id( match.id) if total_users == 0 and total_bets == 0: total_users, total_bets = match_bl.fake_users_and_bets() support_users, oppose_users = match_bl.fake_support_and_oppose_users( total_users) match_json["total_users"] = total_users match_json["total_bets"] = total_bets match_json["bets_side"] = { "support": support_users, "oppose": oppose_users } else: match_json["total_users"] = total_users match_json["total_bets"] = total_bets match_json["bets_side"] = { "support": outcome_bl.count_support_users_play_on_outcome( match.outcomes[0].id), "oppose": outcome_bl.count_against_users_play_on_outcome( match.outcomes[0].id) } response.append(match_json) return response_ok(response) except Exception, ex: return response_error(ex.message)
def update_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) email = request.form.get('email', '') password = request.form.get('password', '') name = request.form.get('name', '') title = request.form.get('title', '') role_id = request.form.get('role_id') t = db.session.query(ReviewType).filter( ReviewType.name == CONST.Type['People']).first() if t is None: return response_error(MESSAGE.TYPE_NOT_IN_DATABASE, CODE.TYPE_NOT_IN_DATABASE) if len(email) > 0: if is_valid_email(email) == False or \ User.find_user_by_email(email) is not None: return response_error(MESSAGE.USER_INVALID_EMAIL, CODE.USER_INVALID_EMAIL) u.email = email if len(password) > 0: if is_valid_password(password) == False: return response_error(MESSAGE.USER_INVALID_PASSWORD, CODE.USER_INVALID_PASSWORD) u.password = hashlib.md5(password).hexdigest() if len(name) > 0: u.name = name if len(title) > 0: u.title = title if role_id is not None and \ Role.find_role_by_id(role_id) is not None: u.role_id = role_id request_size = request.headers.get('Content-length') if request.files and len( request.files) > 0 and request.files['avatar'] is not None: if int( request_size ) <= CONST.UPLOAD_MAX_FILE_SIZE and storage_bl.validate_extension( request.files['avatar'].filename, CONST.UPLOAD_ALLOWED_EXTENSIONS): time = datetime.now().timetuple() seconds = local_to_utc(time) image_name = '{}_{}'.format(seconds, request.files['avatar'].filename) saved_path = storage_bl.handle_upload_file( request.files['avatar'], file_name=image_name) else: return response_error(MESSAGE.FILE_TOO_LARGE, CODE.FILE_TOO_LARGE) gc_services.upload_to_storage(g.GC_STORAGE_BUCKET, saved_path, g.GC_STORAGE_FOLDER, image_name) u.avatar = '{}{}'.format(CONST.BASE_IMAGE_URL, image_name) db.session.commit() return response_ok(u.to_json()) except Exception, ex: db.session.rollback() return response_error(ex.message)
def sign_up(): try: saved_path = None image_name = None email = request.form.get('email', '') password = request.form.get('password', '') name = request.form.get('name', '') title = request.form.get('title', '') 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) t = db.session.query(ReviewType).filter( ReviewType.name == CONST.Type['People']).first() if t is None: return response_error(MESSAGE.TYPE_NOT_IN_DATABASE, CODE.TYPE_NOT_IN_DATABASE) u = User.find_user_by_email(email) if u is None: request_size = request.headers.get('Content-length') if request.files and len( request.files) > 0 and request.files['avatar'] is not None: if int( request_size ) <= CONST.UPLOAD_MAX_FILE_SIZE and storage_bl.validate_extension( request.files['avatar'].filename, CONST.UPLOAD_ALLOWED_EXTENSIONS): time = datetime.now().timetuple() seconds = local_to_utc(time) image_name = '{}_{}'.format( seconds, request.files['avatar'].filename) saved_path = storage_bl.handle_upload_file( request.files['avatar'], file_name=image_name) else: return response_error(MESSAGE.FILE_TOO_LARGE, CODE.FILE_TOO_LARGE) gc_services.upload_to_storage(g.GC_STORAGE_BUCKET, saved_path, g.GC_STORAGE_FOLDER, image_name) u = User(name=name, email=email, password=hashlib.md5(password).hexdigest(), type_id=t.id, title=title, avatar='{}{}'.format(CONST.BASE_IMAGE_URL, image_name) if image_name is not None else None) db.session.add(u) db.session.flush() else: return response_error(MESSAGE.USER_EMAIL_EXIST_ALREADY, CODE.USER_EMAIL_EXIST_ALREADY) response = u.to_json() response['access_token'] = create_access_token(identity=email, fresh=True) db.session.commit() storage_bl.delete_file(saved_path) return response_ok(response) except Exception, ex: db.session.rollback() return response_error(ex.message)
def test_user_reputation(self): t = datetime.now().timetuple() seconds = local_to_utc(t) db.session.query(Handshake).filter(Handshake.outcome_id.in_([1000, 1001, 1002])).delete(synchronize_session="fetch") db.session.query(Shaker).filter(Shaker.handshake_id.in_(\ db.session.query(Handshake.id).filter(Handshake.outcome_id.in_([1000, 1001, 1002]))\ )).delete(synchronize_session="fetch") arr_hs = [] match = Match.find_match_by_id(1) if match is not None: match.date=seconds - 100, match.reportTime=seconds + 100, match.disputeTime=seconds + 200, db.session.flush() else: match = Match( id=1, date=seconds - 100, reportTime=seconds + 100, disputeTime=seconds + 200, ) db.session.add(match) outcome1 = Outcome.find_outcome_by_id(1000) if outcome1 is not None: db.session.delete(outcome1) db.session.commit() outcome1 = Outcome( id=1000, match_id=match.id, result=1, name="1" ) db.session.add(outcome1) db.session.commit() outcome2 = Outcome.find_outcome_by_id(1001) if outcome2 is not None: db.session.delete(outcome2) db.session.commit() outcome2 = Outcome( id=1001, match_id=match.id, result=1, name="1" ) db.session.add(outcome2) db.session.commit() outcome3 = Outcome.find_outcome_by_id(1002) if outcome3 is not None: db.session.delete(outcome3) db.session.commit() outcome3 = Outcome( id=1002, match_id=match.id, result=1, name="1" ) db.session.add(outcome3) db.session.commit() user1 = User.find_user_with_id(88) if user1 is None: user1 = User( id=88 ) db.session.add(user1) db.session.commit() user2 = User.find_user_with_id(89) if user2 is None: user2 = User( id=89 ) db.session.add(user2) db.session.commit() user3 = User.find_user_with_id(100) if user3 is None: user3 = User( id=100 ) db.session.add(user3) db.session.commit() handshake1 = Handshake( hs_type=3, chain_id=4, user_id=user1.id, outcome_id=outcome1.id, odds=1.5, amount=1, currency='ETH', side=outcome1.result, remaining_amount=0, from_address='0x123', status=HandshakeStatus['STATUS_DONE'] ) db.session.add(handshake1) arr_hs.append(handshake1) handshake2 = Handshake( hs_type=3, chain_id=4, user_id=user1.id, outcome_id=outcome2.id, odds=1.5, amount=1, currency='ETH', remaining_amount=0, from_address='0x123', status=HandshakeStatus['STATUS_DONE'], side=outcome2.result ) db.session.add(handshake2) arr_hs.append(handshake2) handshake3 = Handshake( hs_type=3, chain_id=4, user_id=user1.id, outcome_id=outcome2.id, odds=1.5, amount=1, currency='ETH', remaining_amount=0, from_address='0x123', status=HandshakeStatus['STATUS_DONE'], side=outcome2.result ) db.session.add(handshake3) arr_hs.append(handshake3) handshake4 = Handshake( hs_type=3, chain_id=4, user_id=user2.id, outcome_id=outcome1.id, odds=1.5, amount=1, currency='ETH', remaining_amount=0, from_address='0x123', status=HandshakeStatus['STATUS_DONE'], side=outcome1.result ) db.session.add(handshake4) arr_hs.append(handshake4) handshake5 = Handshake( hs_type=3, chain_id=4, user_id=user2.id, outcome_id=outcome1.id, odds=1.5, amount=1, currency='ETH', remaining_amount=0, from_address='0x123', status=HandshakeStatus['STATUS_DONE'], side=outcome1.result ) db.session.add(handshake5) arr_hs.append(handshake5) handshake6 = Handshake( hs_type=3, chain_id=4, user_id=user3.id, outcome_id=outcome3.id, odds=1.5, amount=1, currency='ETH', remaining_amount=0, from_address='0x123', status=HandshakeStatus['STATUS_DONE'], side=outcome3.result + 1 ) db.session.add(handshake6) arr_hs.append(handshake6) handshake7 = Handshake( hs_type=3, chain_id=4, user_id=user3.id, outcome_id=outcome3.id, odds=1.5, amount=1, currency='ETH', remaining_amount=0, from_address='0x123', status=HandshakeStatus['STATUS_DONE'], side=outcome3.result + 1 ) db.session.add(handshake7) arr_hs.append(handshake7) shaker1 = Shaker( shaker_id=user2.id, amount=0.2, currency='ETH', odds=6, side=outcome1.result, handshake_id=handshake1.id, from_address='0x123', chain_id=4, status=HandshakeStatus['STATUS_DONE'] ) db.session.add(shaker1) arr_hs.append(shaker1) db.session.commit() shaker2 = Shaker( shaker_id=user3.id, amount=0.2, currency='ETH', odds=6, side=outcome1.result, handshake_id=handshake1.id, from_address='0x123', chain_id=4, status=HandshakeStatus['STATUS_DONE'] ) db.session.add(shaker2) arr_hs.append(shaker2) db.session.commit() # hs_bets = db.session.query(Handshake.user_id.label("user_id"), bindparam("is_hs", 1), Handshake.free_bet, Handshake.status, Handshake.side, Handshake.from_address, Outcome.id, Outcome.name)\ # .filter(Handshake.outcome_id == Outcome.id)\ # .filter(Outcome.match_id == 1)\ # .filter(Handshake.user_id == user1.id) # s_bets = db.session.query(Shaker.shaker_id.label("user_id"), bindparam("is_hs", 0), Shaker.free_bet, Handshake.status, Shaker.side, Shaker.from_address, Outcome.id, Outcome.name)\ # .filter(Shaker.handshake_id == Handshake.id)\ # .filter(Handshake.outcome_id == Outcome.id)\ # .filter(Outcome.match_id == 1)\ # .filter(Shaker.shaker_id == user1.id) # bets = hs_bets.union_all(s_bets).order_by(Outcome.id.desc()).all() # print bets # Get all user betted this outcome hs_user = db.session.query(Handshake.user_id.label("user_id"))\ .filter(Handshake.outcome_id == outcome1.id) s_user = db.session.query(Shaker.shaker_id.label("user_id"))\ .filter(Shaker.handshake_id == Handshake.id)\ .filter(Handshake.outcome_id == outcome1.id) total_users = hs_user.union_all(s_user).group_by('user_id') # users = db.session.query(User).filter(User.id.in_(hs_user.union_all(s_user).group_by('user_id'))).all() hs_all_bets = db.session.query(Handshake.user_id.label("user_id"), bindparam("is_hs", 1), Handshake.free_bet, Handshake.status.label("status"), Handshake.side.label('side'), Handshake.from_address, Outcome.result.label('outcome_result'))\ .filter(Outcome.id == Handshake.outcome_id) s_all_bets = db.session.query(Shaker.shaker_id.label("user_id"), bindparam("is_hs", 0), Shaker.free_bet, Shaker.status.label("status"), Shaker.side.label('side'), Shaker.from_address, Outcome.result.label('outcome_result'))\ .filter(Shaker.handshake_id == Handshake.id)\ .filter(Outcome.id == Handshake.outcome_id) bets_query = hs_all_bets.union_all(s_all_bets).subquery() bets = db.session.query( bets_query.c.user_id.label('user_id'), func.count(bets_query.c.user_id).label('total_bets'), bindparam("total_bets_win", 0) )\ .filter(bets_query.c.user_id.in_(total_users))\ .filter(bets_query.c.status.in_([HandshakeStatus['STATUS_DONE'], HandshakeStatus['INDUSTRIES_NONE']]))\ .group_by(bets_query.c.user_id) bets_win = db.session.query( bets_query.c.user_id.label('user_id'), bindparam("total_bets", 0), func.count(bets_query.c.user_id).label('total_bets_win'), )\ .filter(bets_query.c.user_id.in_(total_users))\ .filter(bets_query.c.status.in_([HandshakeStatus['STATUS_DONE'], HandshakeStatus['INDUSTRIES_NONE']]))\ .filter(bets_query.c.side == bets_query.c.outcome_result)\ .group_by(bets_query.c.user_id) result_query = bets.union_all(bets_win).subquery() adset_list = db.session.query( result_query.c.user_id, func.sum(result_query.c.total_bets_win).label('total_bets_win'), func.sum(result_query.c.total_bets).label('total_bets') ).group_by(result_query.c.user_id) results = adset_list.all() for item in results: if item.user_id == user1.id: self.assertTrue(item.total_bets_win == 3) for item in arr_hs: db.session.delete(item) db.session.commit() ######################################################################### # # ######################################################################### user_id = 789 user = User.find_user_with_id(789) arr_hs = [] arr_hs.append(match) if user is not None: outcomes = db.session.query(Outcome)\ .filter(Outcome.created_user_id == user_id)\ .all() for oc in outcomes: # arr_delete.extend(oc) hs = db.session.query(Handshake)\ .filter(Outcome.id == oc.id)\ .all() for h in hs: sh = db.session.query(Shaker)\ .filter(Shaker.handshake_id == Handshake.id)\ .filter(Handshake.outcome_id == oc.id)\ .all() for s in sh: db.session.delete(s) db.session.delete(h) db.session.delete(oc) db.session.commit() else: user = User( id=user_id, fcm_token="", payload="" ) db.session.add(user) db.session.commit() outcome1 = Outcome( created_user_id=user_id, match_id=match.id, result=1, hid=789 ) db.session.add(outcome1) arr_hs.append(outcome1) outcome2 = Outcome( created_user_id=user_id, match_id=match.id, result=1, hid=790 ) db.session.add(outcome2) arr_hs.append(outcome2) outcome_dispute = Outcome( created_user_id=user_id, match_id=1, result=-3, hid=793 ) db.session.add(outcome_dispute) db.session.commit() arr_hs.append(outcome_dispute) total_amount = 0 total_dispute_amount = 0 total_bet = 0 total_dispute_bet = 0 total_dispute_event = 1 hs1 = Handshake( hs_type=3, chain_id=4, user_id=user_id, outcome_id=outcome1.id, odds=1.5, amount=0.000227075, currency='ETH', remaining_amount=0, from_address='0x123', status=HandshakeStatus['STATUS_DONE'], side=outcome3.result + 1 ) db.session.add(hs1) db.session.commit() arr_hs.append(hs1) total_amount += 0.000227075 total_bet += 1 shaker2 = Shaker( shaker_id=user_id, amount=0.0001234455, currency='ETH', odds=6, side=outcome1.result, handshake_id=hs1.id, from_address='0x123', chain_id=4, status=HandshakeStatus['STATUS_DONE'] ) db.session.add(shaker2) db.session.commit() arr_hs.append(shaker2) total_amount += 0.0001234455 total_bet += 1 hs2 = Handshake( hs_type=3, chain_id=4, user_id=user_id, outcome_id=outcome2.id, odds=1.5, amount=0.00032612678, currency='ETH', remaining_amount=0, from_address='0x123', status=HandshakeStatus['STATUS_DONE'], side=outcome3.result + 1 ) db.session.add(hs2) db.session.commit() arr_hs.append(hs2) total_amount += 0.00032612678 total_bet += 1 hs_dispute = Handshake( hs_type=3, chain_id=4, user_id=user_id, outcome_id=outcome_dispute.id, odds=1.5, amount=0.0006427075, currency='ETH', remaining_amount=0, from_address='0x123', status=HandshakeStatus['STATUS_DISPUTED'], side=1 ) db.session.add(hs_dispute) db.session.commit() arr_hs.append(hs_dispute) total_amount += 0.0006427075 total_bet += 1 total_dispute_amount += 0.0006427075 total_dispute_bet += 1 hs_dispute2 = Handshake( hs_type=3, chain_id=4, user_id=user_id, outcome_id=outcome1.id, odds=1.5, amount=0.0003227075, currency='ETH', remaining_amount=0, from_address='0x123', status=HandshakeStatus['STATUS_DISPUTE_PENDING'], side=1 ) db.session.add(hs_dispute2) db.session.commit() arr_hs.append(hs_dispute2) total_amount += 0.0003227075 total_bet += 1 total_dispute_amount += 0.0003227075 total_dispute_bet += 1 s_dispute2 = Shaker( shaker_id=user_id, amount=0.00012344379, currency='ETH', odds=6, side=outcome1.result, handshake_id=hs_dispute2.id, from_address='0x123', chain_id=4, status=HandshakeStatus['STATUS_USER_DISPUTED'] ) db.session.add(s_dispute2) db.session.commit() arr_hs.append(s_dispute2) total_amount += 0.00012344379 total_bet += 1 total_dispute_amount += 0.00012344379 total_dispute_bet += 1 with self.client: response = self.client.get( '/reputation/{}'.format(user_id), content_type='application/json', headers={ "Uid": "{}".format(66), "Fcm-Token": "{}".format(123), "Payload": "{}".format(123), }) data = json.loads(response.data.decode()) self.assertTrue(data['status'] == 1) self.assertEqual(response.status_code, 200) self.assertTrue(data['data']['total_events'] == 3) self.assertTrue(data['data']['total_amount'] == total_amount) # self.assertTrue(data['data']['total_bets'] == total_bet) # self.assertTrue(data['data']['total_disputed_amount'] == total_dispute_amount) self.assertTrue(data['data']['total_disputed_bets'] == total_dispute_bet) # self.assertTrue(data['data']['total_disputed_events'] == 1) for item in arr_hs: db.session.delete(item) db.session.commit()