예제 #1
0
async def init_state(app):
    # We have to put "kill" into a dict to prevent getting:
    # DeprecationWarning: Changing state of started or joined application is deprecated
    app["data"] = {"kill": False}

    if "db" not in app:
        app["db"] = None

    app["users"] = {
        "Random-Mover": User(app, bot=True, username="******"),
        "Fairy-Stockfish": User(app, bot=True, username="******"),
        "Discord-Relay": User(app, anon=True, username="******"),
    }
    app["users"]["Random-Mover"].bot_online = True
    app["websockets"] = {}
    app["seeks"] = {}
    app["games"] = {}
    app["chat"] = collections.deque([], 200)
    app["channels"] = set()
    app["highscore"] = {variant: ValueSortedDict(neg) for variant in VARIANTS}
    app["crosstable"] = {}

    # counters for games and users
    app["g_cnt"] = 0
    app["u_cnt"] = 0

    # last game played
    app["tv"] = None

    # fishnet active workers
    app["workers"] = set()
    # fishnet works
    app["works"] = {}
    # fishnet worker tasks
    app["fishnet"] = asyncio.PriorityQueue()
    # fishnet workers monitor
    app["fishnet_monitor"] = {}
    app["fishnet_versions"] = {}
    for key in FISHNET_KEYS:
        app["fishnet_monitor"][FISHNET_KEYS[key]] = collections.deque([], 50)

    rm = app["users"]["Random-Mover"]
    for variant in VARIANTS:
        variant960 = variant.endswith("960")
        variant_name = variant[:-3] if variant960 else variant
        byoyomi = variant == "janggi" or variant.endswith(
            "shogi") or variant == "shogun"
        seek = Seek(rm,
                    variant_name,
                    base=5,
                    inc=3,
                    level=0,
                    chess960=variant960,
                    byoyomi_period=1 if byoyomi else 0)
        app["seeks"][seek.id] = seek
        rm.seeks[seek.id] = seek

    ai = app["users"]["Fairy-Stockfish"]
    loop = asyncio.get_event_loop()

    loop.create_task(BOT_task(ai, app))
    loop.create_task(BOT_task(rm, app))

    # Configure templating.
    app["jinja"] = jinja2.Environment(
        loader=jinja2.FileSystemLoader("templates"),
        autoescape=jinja2.select_autoescape(["html"]))

    if app["db"] is None:
        return

    # Read users and highscore from db
    try:
        cursor = app["db"].user.find()
        async for doc in cursor:
            if doc["_id"] not in app["users"]:
                perfs = doc.get("perfs")
                if perfs is None:
                    perfs = {variant: DEFAULT_PERF for variant in VARIANTS}

                app["users"][doc["_id"]] = User(
                    app,
                    username=doc["_id"],
                    title=doc.get("title"),
                    first_name=doc.get("first_name"),
                    last_name=doc.get("last_name"),
                    country=doc.get("country"),
                    bot=doc.get("title") == "BOT",
                    perfs=perfs,
                    enabled=doc.get("enabled", True))

        db_collections = await app["db"].list_collection_names()

        if "highscore" not in db_collections:
            await generate_highscore(app["db"])
        cursor = app["db"].highscore.find()
        async for doc in cursor:
            app["highscore"][doc["_id"]] = ValueSortedDict(neg, doc["scores"])

        if "crosstable" not in db_collections:
            await generate_crosstable(app["db"])
        cursor = app["db"].crosstable.find()
        async for doc in cursor:
            app["crosstable"][doc["_id"]] = doc

    except Exception:
        print("Maybe mongodb is not running...")
        raise
예제 #2
0
async def init_state(app):
    # We have to put "kill" into a dict to prevent getting:
    # DeprecationWarning: Changing state of started or joined application is deprecated
    app["data"] = {"kill": False}

    if "db" not in app:
        app["db"] = None

    app["users"] = {
        "Random-Mover": User(app, bot=True, username="******"),
        "Fairy-Stockfish": User(app, bot=True, username="******"),
        "Discord-Relay": User(app, anon=True, username="******"),
    }
    app["users"]["Random-Mover"].online = True
    app["lobbysockets"] = {}
    app["seeks"] = {}
    app["games"] = {}
    app["invites"] = {}
    app["chat"] = collections.deque([], 100)
    app["game_channels"] = set()
    app["invite_channels"] = set()
    app["highscore"] = {variant: ValueSortedDict(neg) for variant in VARIANTS}
    app["crosstable"] = {}
    app["stats"] = {}

    # counters for games
    app["g_cnt"] = 0

    # last game played
    app["tv"] = None

    # fishnet active workers
    app["workers"] = set()
    # fishnet works
    app["works"] = {}
    # fishnet worker tasks
    app["fishnet"] = asyncio.PriorityQueue()
    # fishnet workers monitor
    app["fishnet_monitor"] = {}
    app["fishnet_versions"] = {}
    for key in FISHNET_KEYS:
        app["fishnet_monitor"][FISHNET_KEYS[key]] = collections.deque([], 50)

    rm = app["users"]["Random-Mover"]
    for variant in VARIANTS:
        variant960 = variant.endswith("960")
        variant_name = variant[:-3] if variant960 else variant
        byoyomi = variant.endswith("shogi") or variant in ("dobutsu",
                                                           "gorogoro",
                                                           "janggi", "shogun")
        seek = Seek(rm,
                    variant_name,
                    base=5,
                    inc=30 if byoyomi else 3,
                    level=0,
                    chess960=variant960,
                    byoyomi_period=1 if byoyomi else 0)
        app["seeks"][seek.id] = seek
        rm.seeks[seek.id] = seek

    ai = app["users"]["Fairy-Stockfish"]

    asyncio.create_task(BOT_task(ai, app))
    asyncio.create_task(BOT_task(rm, app))

    # Configure templating.
    app["jinja"] = {}
    base = os.path.dirname(__file__)
    for lang in LANGUAGES:
        # Generate compiled mo file
        folder = os.path.join(base, "../lang/", lang, "LC_MESSAGES")
        poname = os.path.join(folder, "server.po")
        moname = os.path.join(folder, "server.mo")
        try:
            with open(poname, 'rb') as po_file:
                po_lines = [
                    line for line in po_file if line[:8] != b"#, fuzzy"
                ]
                mo = Msgfmt(po_lines).get()
                with open(moname, 'wb') as mo_file:
                    mo_file.write(mo)
        except PoSyntaxError:
            log.error("PoSyntaxError in %s", poname)

        # Create translation class
        try:
            translation = gettext.translation("server",
                                              localedir="lang",
                                              languages=[lang])
        except FileNotFoundError:
            log.warning("Missing translations file for lang %s", lang)
            translation = gettext.NullTranslations()

        env = jinja2.Environment(enable_async=True,
                                 extensions=['jinja2.ext.i18n'],
                                 loader=jinja2.FileSystemLoader("templates"),
                                 autoescape=jinja2.select_autoescape(["html"]))
        env.install_gettext_translations(translation, newstyle=True)
        env.globals["static"] = static_url

        app["jinja"][lang] = env

    if app["db"] is None:
        return

    # Read users and highscore from db
    try:
        cursor = app["db"].user.find()
        async for doc in cursor:
            if doc["_id"] not in app["users"]:
                perfs = doc.get("perfs")
                if perfs is None:
                    perfs = {variant: DEFAULT_PERF for variant in VARIANTS}

                app["users"][doc["_id"]] = User(
                    app,
                    username=doc["_id"],
                    title=doc.get("title"),
                    first_name=doc.get("first_name"),
                    last_name=doc.get("last_name"),
                    country=doc.get("country"),
                    bot=doc.get("title") == "BOT",
                    perfs=perfs,
                    enabled=doc.get("enabled", True))

        db_collections = await app["db"].list_collection_names()

        if "highscore" not in db_collections:
            await generate_highscore(app["db"])
        cursor = app["db"].highscore.find()
        async for doc in cursor:
            app["highscore"][doc["_id"]] = ValueSortedDict(neg, doc["scores"])

        if "crosstable" not in db_collections:
            await generate_crosstable(app["db"])
        cursor = app["db"].crosstable.find()
        async for doc in cursor:
            app["crosstable"][doc["_id"]] = doc

        await app["db"].game.create_index("us")
        await app["db"].game.create_index("v")
        await app["db"].game.create_index("y")
        await app["db"].game.create_index("by")

    except Exception:
        print("Maybe mongodb is not running...")
        raise
예제 #3
0
async def init_state(app):
    # We have to put "kill" into a dict to prevent getting:
    # DeprecationWarning: Changing state of started or joined application is deprecated
    app["data"] = {"kill": False}
    app["date"] = {"startedAt": datetime.now(timezone.utc)}

    if "db" not in app:
        app["db"] = None

    app["users"] = {
        "Random-Mover": User(app, bot=True, username="******"),
        "Fairy-Stockfish": User(app, bot=True, username="******"),
        "Discord-Relay": User(app, anon=True, username="******"),
    }
    app["users"]["Random-Mover"].online = True
    app["lobbysockets"] = {
    }  # one dict only! {user.username: user.tournament_sockets, ...}
    app["lobbychat"] = collections.deque([], MAX_CHAT_LINES)

    app["tourneysockets"] = {
    }  # one dict per tournament! {tournamentId: {user.username: user.tournament_sockets, ...}, ...}
    app["tourneynames"] = {
    }  # cache for profile game list page {tournamentId: tournament.name, ...}
    app["tournaments"] = {}
    app["tourneychat"] = {
    }  # one deque per tournament! {tournamentId: collections.deque([], MAX_CHAT_LINES), ...}

    app["seeks"] = {}
    app["games"] = {}
    app["invites"] = {}
    app["game_channels"] = set()
    app["invite_channels"] = set()
    app["highscore"] = {variant: ValueSortedDict(neg) for variant in VARIANTS}
    app["crosstable"] = {}
    app["shield"] = {}
    app["shield_owners"] = {}  # {variant: username, ...}

    app["stats"] = {}
    app["stats_humans"] = {}

    # counters for games
    app["g_cnt"] = [0]

    # last game played
    app["tv"] = None

    app["twitch"] = Twitch(app)
    if not DEV:
        await app["twitch"].init_subscriptions()

    # fishnet active workers
    app["workers"] = set()
    # fishnet works
    app["works"] = {}
    # fishnet worker tasks
    app["fishnet"] = asyncio.PriorityQueue()
    # fishnet workers monitor
    app["fishnet_monitor"] = {}
    app["fishnet_versions"] = {}
    for key in FISHNET_KEYS:
        app["fishnet_monitor"][FISHNET_KEYS[key]] = collections.deque([], 50)

    rm = app["users"]["Random-Mover"]
    ai = app["users"]["Fairy-Stockfish"]

    asyncio.create_task(BOT_task(ai, app))
    asyncio.create_task(BOT_task(rm, app))

    # Configure templating.
    app["jinja"] = {}
    base = os.path.dirname(__file__)
    for lang in LANGUAGES:
        # Generate compiled mo file
        folder = os.path.join(base, "../lang/", lang, "LC_MESSAGES")
        poname = os.path.join(folder, "server.po")
        moname = os.path.join(folder, "server.mo")
        try:
            with open(poname, 'rb') as po_file:
                po_lines = [
                    line for line in po_file if line[:8] != b"#, fuzzy"
                ]
                mo = Msgfmt(po_lines).get()
                with open(moname, 'wb') as mo_file:
                    mo_file.write(mo)
        except PoSyntaxError:
            log.error("PoSyntaxError in %s", poname)

        # Create translation class
        try:
            translation = gettext.translation("server",
                                              localedir="lang",
                                              languages=[lang])
        except FileNotFoundError:
            log.warning("Missing translations file for lang %s", lang)
            translation = gettext.NullTranslations()

        env = jinja2.Environment(enable_async=True,
                                 extensions=['jinja2.ext.i18n'],
                                 loader=jinja2.FileSystemLoader("templates"),
                                 autoescape=jinja2.select_autoescape(["html"]))
        env.install_gettext_translations(translation, newstyle=True)
        env.globals["static"] = static_url

        app["jinja"][lang] = env

    if app["db"] is None:
        return

    # Read tournaments, users and highscore from db
    try:
        cursor = app["db"].user.find()
        async for doc in cursor:
            if doc["_id"] not in app["users"]:
                perfs = doc.get("perfs")
                if perfs is None:
                    perfs = {variant: DEFAULT_PERF for variant in VARIANTS}

                app["users"][doc["_id"]] = User(app,
                                                username=doc["_id"],
                                                title=doc.get("title"),
                                                bot=doc.get("title") == "BOT",
                                                perfs=perfs,
                                                enabled=doc.get(
                                                    "enabled", True))

        cursor = app["db"].tournament.find()
        cursor.sort('startsAt', -1)
        counter = 0
        async for doc in cursor:
            if doc["status"] in (T_CREATED, T_STARTED):
                await load_tournament(app, doc["_id"])
                counter += 1
                if counter > 3:
                    break

        await generate_shield(app)

        db_collections = await app["db"].list_collection_names()

        # if "highscore" not in db_collections:
        # Always create new highscore lists on server start
        await generate_highscore(app["db"])
        cursor = app["db"].highscore.find()
        async for doc in cursor:
            app["highscore"][doc["_id"]] = ValueSortedDict(neg, doc["scores"])

        if "crosstable" not in db_collections:
            await generate_crosstable(app["db"])
        cursor = app["db"].crosstable.find()
        async for doc in cursor:
            app["crosstable"][doc["_id"]] = doc

        await app["db"].game.create_index("us")
        await app["db"].game.create_index("v")
        await app["db"].game.create_index("y")
        await app["db"].game.create_index("by")

    except Exception:
        print("Maybe mongodb is not running...")
        raise

    # create test tournament
    if 1:
        pass