Exemplo n.º 1
0
def get_winner(game):
    deposits = game.deposits.all()
    win_num = -1
    winner = None
    if game.win_ticket == 0:
        win_ticket = math.floor(
            (game.total_tickets - 0.0000000001) * (game.percentage / 100))
        game.win_ticket = win_ticket if win_ticket >= 1 else 1
        game.save()
    for i, d in enumerate(deposits):
        if d.tickets_begin <= game.win_ticket <= d.tickets_end:
            win_num = d.team
            winner = d.steamer
            break

    win_deposits = game.deposits.filter(steamer__steamid=winner.steamid).all()
    win_deposit_amount = sum([wd.amount for wd in win_deposits])

    ts = aware_datetime_to_timestamp(game.win_ts)
    coinflip_winner = {
        'num': win_num,
        'totalTickets': game.total_tickets,
        'ts': ts
    }
    jackpot_winner = {
        'steamer': SteamerSerializer(winner).data,
        'amount': round(game.total_amount, 2),
        'chance':
        '{0:.2f}'.format(win_deposit_amount / game.total_amount * 100)
    }
    return coinflip_winner, jackpot_winner
Exemplo n.º 2
0
def request_store(record, steamer):
    dt_now = dt.now()
    ts = aware_datetime_to_timestamp(dt_now)
    user = SteamerSerializer(steamer, fields=(
        'steamid',
        'tradeurl',
    )).data
    items = record.items.all()
    items_data = [
        PropItemSerializer(i,
                           fields=('uid', 'name', 'classid', 'appid',
                                   'contextid', 'assetid')).data for i in items
    ]
    trade_request = {
        'status': TradeStatus.Initialed.value,
        'trade_no': None,
        'steamer': user,
        'uid': record.uid,
        'message': record.security_code,
        'myItems': [],
        'theirItems': items_data,
        'steamid': '',
    }
    r = get_redis()
    key = 'trade_{0}_{1}_{2}'.format(record.uid, steamer.steamid, ts)
    r.set(key, json.dumps(trade_request, encoding='utf-8'))
    r.lpush(_trade_list_key, key)
    _logger.info(u'request trade {0} items from {1} on {2}'.format(
        len(items), steamer.personaname, steamer.tradeurl))
Exemplo n.º 3
0
def format_jackpot_game(game, animate=False, **kwargs):
    run_ts = None
    dt_now = dt.now()
    least_sec = settings.JACKPOT_COUNTDOWN
    if game.run_ts:
        run_ts = aware_datetime_to_timestamp(game.run_ts)
        least_span = (dt_now - game.run_ts).seconds
        if least_span < settings.JACKPOT_COUNTDOWN:
            least_sec = settings.JACKPOT_COUNTDOWN - least_span
    ret = {
        'uid': game.uid,
        'hash': game.hash,
        'secret': None,
        'percentage': None,
        'winner': None,
        'deposit': None,
        'deposits': [],
        'total_amount': round(game.total_amount, 2),
        'total_items': game.total_items,
        'run_ts': run_ts,
        'totalTickets': game.total_tickets,
        'countdown': settings.JACKPOT_COUNTDOWN,
        'least_sec': least_sec
    }

    deposit_data = []
    deposits = game.deposits.all().order_by('accept_time')
    for i, d in enumerate(deposits):
        dep_serializer = DepositSerializer(
            d, fields=['uid', 'team', 'steamer', 'amount', 'items', 'gid'])
        dep_data = dep_serializer.data
        dep_data['color'] = get_team_color(i)
        deposit_data.append(dep_data)
    ret['deposits'] = deposit_data
    if game.end:
        cf, jk = get_winner(game)
        ret['winner'] = jk
        ret['secret'] = game.secret
        ret['percentage'] = '{0:.13f}'.format(game.percentage)
        if animate:
            joiners, win_index = format_jackpot_joiners(game, jk)
            ret['deposit'] = {
                'uid': game.uid,
                'joiners': joiners,
                'win_index': win_index
            }
    return ret
Exemplo n.º 4
0
def format_coinflip_game_all(game, end=False, **kwargs):
    dt_now = dt.now()
    ts = aware_datetime_to_timestamp(dt_now)
    ret = {
        'hash': game.hash,
        'closed': False,
        'date': dt_now.strftime('%Y-%m-%d %H:%M:%S'),
        'gid': game.uid,
        'ts_get': ts,
        'winner': None,
        'joined': None,
        'deposit': []
    }
    total_amount = 0.0
    total_items = 0
    deposits = game.deposits.all()
    items = []
    closed = True if len(deposits) >= 2 else False
    for deposit in deposits:
        deposit_s = DepositSerializer(deposit)
        deposit_data = deposit_s.data
        steamer_s = SteamerSerializer(deposit.steamer)
        deposit_data.update(steamer_s.data)
        deposit_data['totalItems'] = len(deposit_data['items'])
        deposit_data['totalAmount'] = sum(d['amount']
                                          for d in deposit_data['items'])
        ret['deposit'].append(deposit_data)
        total_items += deposit_data['totalItems']
        total_amount += deposit_data['totalAmount']
        items.extend(deposit_data['items'])
    amount_o = {'min': total_amount * 0.9, 'max': total_amount * 1.1}
    items = sorted(items, key=lambda x: x['amount'], reverse=True)
    items_more = total_items - 6
    ret.update({
        'totalItems': total_items,
        'totalAmount': total_amount,
        'closed': closed,
        'amount_o': amount_o,
        'itemsShow': items[:6],
        'itemsMore': items_more if items_more > 0 else 0
    })
    return ret
Exemplo n.º 5
0
def format_deposit(deposit, end=False, **kwargs):
    dt_now = dt.now()
    ts = aware_datetime_to_timestamp(dt_now)
    ret = {
        'hash': deposit.game.hash,
        'closed': False,
        'date': dt_now.strftime('%Y-%m-%d %H:%M:%S'),
        'gid': deposit.game.id,
        'ts_get': ts,
        'winner': {},
        'joined': {},
        'deposit': []
    }
    deposit_s = DepositSerializer(deposit)
    deposit_data = deposit_s.data
    steamer_s = SteamerSerializer(deposit.steamer)
    deposit_data.update(steamer_s.data)
    deposit_data['totalItems'] = len(deposit_data['items'])
    deposit_data['totalAmount'] = sum(d['amount']
                                      for d in deposit_data['items'])
    ret['deposit'].append(deposit_data)
    return ret
Exemplo n.º 6
0
def coinflip_countdown_checker():
    r = get_redis()
    while True:
        try:
            if not is_connection_usable():
                connection.close()

            m = get_maintenance()
            if not m:
                keys = r.smembers(_cf_game_set)
                for key in keys:
                    game_data = r.get(key)
                    if not game_data:
                        continue
                    game = json.loads(game_data, encoding='utf-8')
                    winner = game.get('winner', None)
                    time_now = dt.now()
                    ts_now = aware_datetime_to_timestamp(time_now)
                    canceled = False
                    if winner:
                        ts = game['win_ts']
                        expires = settings.COINFLIP_END_EXPIRE - (ts_now - ts)
                    else:
                        ts = game['ts_get']
                        expires = settings.COINFLIP_EXPIRE_TIMEOUT - (ts_now -
                                                                      ts)
                        canceled = expires <= 0
                    if expires <= 0:
                        r.srem(_cf_game_set, key)
                        r.delete(key)
                    if canceled:
                        ws_send_cf_remove(game['gid'])
                        trade_items_back_to_joiners(game['gid'])
        except Exception as e:
            _logger.exception(e)
        finally:
            time.sleep(60)
Exemplo n.º 7
0
def format_coinflip_game(game, **kwargs):
    user = kwargs.get('user', None)
    end_only = kwargs.get('end_only', False)
    dt_now = dt.now()
    ts = aware_datetime_to_timestamp(dt_now)
    ts_create = aware_datetime_to_timestamp(game.create_time)
    expires_at = game.create_time + timedelta(
        minutes=settings.COINFLIP_EXPIRE_TIMEOUT)
    expires_ts = aware_datetime_to_timestamp(expires_at)
    ret = {
        'no': game.id,
        'gid': game.uid,
        'hash': game.hash,
        'ts_create': ts_create,
        'ts_get': ts,
        'winner': None,
        'deposits': [],
        'joined': None,
        'total_amount': game.total_amount,
        'expires_at': expires_ts
    }
    deposits = game.deposits.filter(
        join_status__gt=10).order_by('create_time').all()
    if len(deposits) == 0:
        return None

    if end_only and len(deposits) < 2:
        return None

    status = game.status
    joiner = None
    user_deposit = None
    game_full = False
    for deposit in deposits:
        deposit_s = DepositSerializer(
            deposit,
            fields=['uid', 'team', 'steamer', 'amount', 'items', 'gid'])
        deposit_data = deposit_s.data
        if deposit.status == TradeStatus.Accepted.value:
            ret['deposits'].append(deposit_data)

        if deposit.status != TradeStatus.Accepted.value:
            joiner = deposit
        if user and user.steamid == deposit.steamer.steamid:
            user_deposit = deposit_data
    ret['user_deposit'] = user_deposit

    if game.end:
        game_full = True
        winner, team = get_coinflip_winner(game)
        ret['winner'] = SteamerSerializer(winner).data
        ret['winner'].update({'team': team})
        ret['win_ts'] = aware_datetime_to_timestamp(game.win_ts)
        ret['percentage'] = '{0:.13f}'.format(game.percentage)
        ret['secret'] = game.secret
        ret['total_tickets'] = game.total_tickets
    ret['status'] = status
    ret['full'] = game_full

    joined = {
        'status': 0,
    }
    if joiner:
        joined_least = (dt_now - joiner.create_time).seconds
        joined.update({
            'status': 1,
            'expired': False,
            "ts": ts,
            'least': settings.DEPOSIT_TIMEOUT - joined_least,
            'max': settings.DEPOSIT_TIMEOUT,
            'steamer': SteamerSerializer(joiner.steamer).data
        })
    ret['joined'] = joined
    return ret