Beispiel #1
0
def update_match(match_id: int, left_id: int, left_games: int, right_id: int,
                 right_games: int) -> None:
    db().begin('update_match')
    update_games(match_id, left_id, left_games)
    update_games(match_id, right_id, right_games)
    db().commit('update_match')
    redis.clear(f'decksite:deck:{left_id}', f'decksite:deck:{right_id}')
Beispiel #2
0
def post_archetypes() -> wrappers.Response:
    search_results: List[Deck] = []
    if request.form.get('deck_id') is not None:
        archetype_ids = request.form.getlist('archetype_id')
        # Adjust archetype_ids if we're assigning multiple decks to the same archetype.
        if len(archetype_ids) == 1 and len(request.form.getlist('deck_id')) > 1:
            archetype_ids = archetype_ids * len(request.form.getlist('deck_id'))
        for deck_id in request.form.getlist('deck_id'):
            archetype_id = archetype_ids.pop(0)
            if archetype_id:
                archs.assign(deck_id, archetype_id, auth.person_id())
                redis.clear(f'decksite:deck:{deck_id}')
    elif request.form.get('q') is not None and request.form.get('notq') is not None:
        search_results = ds.load_decks_by_cards(cast(str, request.form.get('q')).splitlines(), cast(str, request.form.get('notq')).splitlines())
    elif request.form.get('find_conflicts') is not None:
        search_results = ds.load_conflicted_decks()
    elif request.form.get('rename_to') is not None:
        archs.rename(cast_int(request.form.get('archetype_id')), cast(str, request.form.get('rename_to')))
    elif request.form.get('new_description') is not None:
        archs.update_description(cast_int(request.form.get('archetype_id')), cast(str, request.form.get('new_description')))
    elif request.form.getlist('archetype_id') is not None and len(request.form.getlist('archetype_id')) == 2:
        archs.move(request.form.getlist('archetype_id')[0], request.form.getlist('archetype_id')[1])
    elif request.form.get('parent') is not None:
        archs.add(cast(str, request.form.get('name')), cast_int(request.form.get('parent')))
    else:
        raise InvalidArgumentException('Did not find any of the expected keys in POST to /admin/archetypes: {f}'.format(f=request.form))
    return edit_archetypes(search_results, request.form.get('q', ''), request.form.get('notq', ''))
Beispiel #3
0
def post_archetypes():
    search_results = []
    if request.form.get('deck_id') is not None:
        archetype_ids = request.form.getlist('archetype_id')
        # Adjust archetype_ids if we're assigning multiple decks to the same archetype.
        if len(archetype_ids) == 1 and len(
                request.form.getlist('deck_id')) > 1:
            archetype_ids = archetype_ids * len(
                request.form.getlist('deck_id'))
        for deck_id in request.form.getlist('deck_id'):
            archetype_id = archetype_ids.pop(0)
            if archetype_id:
                archs.assign(deck_id, archetype_id)
                redis.clear(f'decksite:deck:{deck_id}')
    elif request.form.get('q') is not None and request.form.get(
            'notq') is not None:
        search_results = ds.load_decks_by_cards(
            request.form.get('q').splitlines(),
            request.form.get('notq').splitlines())
    elif request.form.getlist('archetype_id') is not None and len(
            request.form.getlist('archetype_id')) == 2:
        archs.move(
            request.form.getlist('archetype_id')[0],
            request.form.getlist('archetype_id')[1])
    elif request.form.get('parent') is not None:
        archs.add(request.form.get('name'), request.form.get('parent'))
    else:
        raise InvalidArgumentException(
            'Did not find any of the expected keys in POST to /admin/archetypes: {f}'
            .format(f=request.form))
    return edit_archetypes(search_results, request.form.get('q', ''),
                           request.form.get('notq', ''))
Beispiel #4
0
def delete_match(match_id: int) -> None:
    deck_ids = db().values(
        'SELECT deck_id FROM deck_match WHERE match_id = %s', [match_id])
    sql = 'DELETE FROM `match` WHERE id = %s'
    db().execute(sql, [match_id])
    for deck_id in deck_ids:
        redis.clear(f'decksite:deck:{deck_id}')
Beispiel #5
0
def insert_match(dt: datetime.datetime,
                 left_id: int,
                 left_games: int,
                 right_id: int,
                 right_games: int,
                 round_num: Optional[int] = None,
                 elimination: Optional[int] = None,
                 mtgo_match_id: Optional[int] = None) -> int:
    if left_games == right_games:
        raise InvalidDataException('`insert_match` does not support draws.')
    winner_id = left_id if left_games > right_games else right_id
    loser_id = left_id if left_games < right_games else right_id
    db().begin('insert_match')
    match_id = db().insert(
        'INSERT INTO `match` (`date`, `round`, elimination, mtgo_id) VALUES (%s, %s, %s, %s)',
        [dtutil.dt2ts(dt), round_num, elimination, mtgo_match_id])
    update_cache(left_id, left_games, right_games, dt=dt)
    update_cache(right_id, right_games, left_games, dt=dt)
    sql = 'INSERT INTO deck_match (deck_id, match_id, games) VALUES (%s, %s, %s)'
    db().execute(sql, [left_id, match_id, left_games])
    if right_id is not None:  # Don't insert matches or adjust Elo for the bye.
        db().execute(sql, [right_id, match_id, right_games])
        elo.adjust_elo(winner_id, loser_id)
    db().commit('insert_match')
    redis.clear(f'decksite:deck:{left_id}')
    if right_id is not None:
        redis.clear(f'decksite:deck:{right_id}')
    return match_id
Beispiel #6
0
def set_issue_bbt(number: int, text: Optional[str]) -> None:
    key = f'modobugs:bug_blog_text:{number}'
    if text is None:
        ISSUE_CODES.pop(number, None)
        redis.clear(key)
    else:
        ISSUE_CODES[number] = text
        redis.store(key, text, ex=1200)
Beispiel #7
0
 async def background_task_reboot(self) -> None:
     do_reboot_key = 'discordbot:do_reboot'
     if redis.get_bool(do_reboot_key):
         redis.clear(do_reboot_key)
     while self.is_ready():
         if redis.get_bool(do_reboot_key):
             print('Got request to reboot from redis')
             await self.logout()
         await asyncio.sleep(60)
def run() -> None:
    all_decks = deck.load_decks()
    for d in all_decks:
        # Recalculate all hashes, in case they've changed.  Or we've changed the default sort order.
        cards = {'maindeck': d['maindeck'], 'sideboard': d['sideboard']}
        deckhash = hashlib.sha1(repr(cards).encode('utf-8')).hexdigest()
        if d['decklist_hash'] != deckhash:
            print(f"{d.id}: hash was {d['decklist_hash']} now {deckhash}")
            db().execute('UPDATE deck SET decklist_hash = %s WHERE id = %s', [deckhash, d['id']])
            redis.clear(f'decksite:deck:{d.id}')
def retire_deck(d):
    try:
        if d.wins == 0 and d.losses == 0 and d.draws == 0:
            sql = 'DELETE FROM deck WHERE id = %s'
            db().execute(sql, [d.id])
            return
    except DatabaseException:
        pass
    sql = 'UPDATE `deck` SET `retired` = 1 WHERE id = %s'
    db().execute(sql, [d.id])
    redis.clear(f'decksite:deck:{d.id}')
def run():
    multiverse.update_cache()
    oracle.init()
    ds = deck.load_decks()
    for d in ds:
        redis.clear(f'decksite:deck:{d.id}')
        deck.prime_cache(d)
    archetype.preaggregate()
    card.preaggregate()
    deck.preaggregate_omw()
    return 'Done'
def run() -> None:
    multiverse.update_cache()
    oracle.init()
    ds = deck.load_decks()
    for d in ds:
        redis.clear(f'decksite:deck:{d.id}')
        deck.prime_cache(d)
        redis.clear(f'decksite:deck:{d.id}')
    archetype.preaggregate()
    person.preaggregate()
    card.preaggregate()
    deck.preaggregate_omw()
    rule.cache_all_rules()
async def modofail(ctx: MtgContext, args: Optional[str]) -> None:
    """Ding!"""
    if args is not None and args.lower() == 'reset':
        redis.clear(f'modofail:{ctx.guild}')
    if hasattr(ctx.author, 'voice') and ctx.author.voice is not None and ctx.author.voice.channel is not None:
        voice_channel = ctx.author.voice.channel
        voice = ctx.channel.guild.voice_client
        if voice is None:
            voice = await voice_channel.connect()
        elif voice.channel != voice_channel:
            voice.move_to(voice_channel)
        voice.play(FFmpegPCMAudio('ding.ogg'))
    n = redis.increment(f'modofail:{ctx.guild}')
    redis.expire(f'modofail:{ctx.guild}', 3600)
    await ctx.send(f':bellhop: **MODO fail** {n}')
Beispiel #13
0
def prime_cache(d: Deck) -> None:
    set_colors(d)
    colors_s = json.dumps(d.colors)
    colored_symbols_s = json.dumps(d.colored_symbols)
    set_legality(d)
    legal_formats_s = json.dumps(list(d.legal_formats))
    normalized_name = deck_name.normalize(d)
    # If this is a new deck we're going to make a new record. If it's an existing deck we might as well update a few things that might have changed implementation but should otherwise be static. But leave wins/draws/losses/active date alone.
    sql = """
        INSERT INTO
            deck_cache (deck_id, normalized_name, colors, colored_symbols, legal_formats, wins, draws, losses, active_date)
        VALUES
            (%s, %s, %s, %s, %s, %s, %s, %s, %s)
        ON DUPLICATE KEY UPDATE normalized_name = %s, colors = %s, colored_symbols = %s, legal_formats = %s
    """
    db().execute(sql, [d.id, normalized_name, colors_s, colored_symbols_s, legal_formats_s, 0, 0, 0, dtutil.dt2ts(d.created_date), normalized_name, colors_s, colored_symbols_s, legal_formats_s])
    # If it was worth priming the in-db cache it's worth busting the in-memory cache to pick up the changes.
    redis.clear(f'decksite:deck:{d.id}')
Beispiel #14
0
def update_match(match_id: int, left_id: int, left_games: int, right_id: int,
                 right_games: int) -> None:
    db().begin('update_match')
    m = load_match(match_id, left_id)
    prev_winner = winner(m.deck_id, m.game_wins, m.opponent_deck_id,
                         m.game_losses)
    new_winner = winner(left_id, left_games, right_id, right_games)
    update_games(match_id, left_id, left_games)
    update_games(match_id, right_id, right_games)
    if new_winner != prev_winner:
        update_cache(m.deck_id, m.game_wins, m.game_losses, delete=True)
        update_cache(m.opponent_deck_id,
                     m.game_losses,
                     m.game_wins,
                     delete=True)
        update_cache(left_id, left_games, right_games)
        update_cache(right_id, right_games, left_games)
    db().commit('update_match')
    redis.clear(f'decksite:deck:{left_id}', f'decksite:deck:{right_id}')
Beispiel #15
0
def delete_match(match_id: int) -> None:
    db().begin('delete_match')
    rs = db().select(
        'SELECT deck_id, games FROM deck_match WHERE match_id = %s',
        [match_id])
    if not rs:
        raise TooFewItemsException(
            'No deck_match entries found for match_id `{match_id}`')
    left_id = rs[0]['deck_id']
    left_games = rs[0]['games']
    if len(rs) > 1:
        right_id = rs[1]['deck_id']
        right_games = rs[1]['games']
    else:
        right_id, right_games = 0, 0
    update_cache(left_id, left_games, right_games, delete=True)
    update_cache(right_id, right_games, left_games, delete=True)
    sql = 'DELETE FROM `match` WHERE id = %s'
    db().execute(sql, [match_id])
    db().commit('delete_match')
    if rs:
        redis.clear(f'decksite:deck:{left_id}', f'decksite:deck:{right_id}')
Beispiel #16
0
def prime_cache(d: Deck) -> None:
    set_colors(d)
    colors_s = json.dumps(d.colors)
    colored_symbols_s = json.dumps(d.colored_symbols)
    set_legality(d)
    legal_formats_s = json.dumps(list(d.legal_formats))
    normalized_name = deck_name.normalize(d)
    db().begin()
    db().execute('DELETE FROM deck_cache WHERE deck_id = %s', [d.id])
    sql = """
        INSERT INTO
            deck_cache (deck_id, normalized_name, colors, colored_symbols, legal_formats, wins, draws, losses, active_date)
        VALUES
            (%s, %s, %s, %s, %s, %s, %s, %s, %s)
    """
    db().execute(sql, [
        d.id, normalized_name, colors_s, colored_symbols_s, legal_formats_s, 0,
        0, 0,
        dtutil.dt2ts(d.created_date)
    ])
    db().commit()
    # If it was worth priming the in-db cache it's worth busting the in-memory cache to pick up the changes.
    redis.clear(f'decksite:deck:{d.id}')
def clear_redis(clear_files: bool = False) -> None:
    redis.clear(*redis.keys('decksite:rotation:summary:*'))
    if clear_files:
        redis.clear(*redis.keys('decksite:rotation:file:*'))
def unlock(channel_id: int) -> None:
    redis.clear(f'discordbot:p1p1:{channel_id}')
def post_reassign(deck_id: int, archetype_id: int) -> Response:
    archs.assign(deck_id, archetype_id)
    redis.clear(f'decksite:deck:{deck_id}')
    return return_json({'success': True, 'deck_id': deck_id})
Beispiel #20
0
def retire_deck(d: Deck) -> None:
    sql = 'UPDATE `deck` SET `retired` = 1, updated_date = UNIX_TIMESTAMP(NOW()) WHERE id = %s'
    db().execute(sql, [d.id])
    redis.clear(f'decksite:deck:{d.id}')
Beispiel #21
0
def post_reassign() -> str:
    deck_id = int(request.form.get('deck_id'))
    archetype_id = int(request.form.get('archetype_id'))
    archs.assign(deck_id, archetype_id)
    redis.clear(f'decksite:deck:{deck_id}')
    return return_json({'success': True, 'deck_id': deck_id})