Пример #1
0
    async def _update_sql(self, prev_version: Version) -> None:
        """Apply any structural changes to sql since the last startup."""
        if self.version == prev_version:
            # already up to date.
            return

        # version changed; there may be sql changes.
        content = SQL_UPDATES_FILE.read_text()

        queries = []
        q_lines = []

        current_ver = None

        for line in content.splitlines():
            if not line:
                continue

            if line.startswith('#'):
                # may be normal comment or new version
                if rgx := re.fullmatch(r'^# v(?P<ver>\d+\.\d+\.\d+)$', line):
                    current_ver = Version.from_str(rgx['ver'])

                continue
            elif not current_ver:
                continue
Пример #2
0
async def run_server(addr: Address) -> None:
    glob.version = Version(2, 8, 5)
    glob.http = aiohttp.ClientSession(json_serialize=orjson.dumps)

    loop = asyncio.get_event_loop()

    try:
        loop.add_signal_handler(signal.SIGINT, loop.stop)
        loop.add_signal_handler(signal.SIGTERM, loop.stop)
    except NotImplementedError:
        pass

    glob.db = AsyncSQLPoolWrapper()
    await glob.db.connect(**glob.config.mysql)

    # create our bot & append it to the global player list.
    glob.bot = Player(id=1, name='Aika', priv=Privileges.Normal)
    glob.bot.last_recv_time = 0x7fffffff

    glob.players.add(glob.bot)

    # add all channels from db.
    async for chan in glob.db.iterall('SELECT * FROM channels'):
        await glob.channels.add(Channel(**chan))

    # run background process to
    # disconnect inactive clients.
    loop.create_task(disconnect_inactive())

    async with AsyncTCPServer(addr) as glob.serv:
        log(f'Gulag v{glob.version} online!', AnsiRGB(0x00ff7f))
        async for conn in glob.serv.listen(glob.config.max_conns):
            loop.create_task(handle_conn(conn))
Пример #3
0
    async def _update_sql(self, prev_version: Version) -> None:
        """Apply any structural changes to the database since the last startup."""
        if self.version == prev_version:
            # already up to date.
            return

        # version changed; there may be sql changes.
        with open(SQL_UPDATES_FILE, 'r') as f:
            content = f.read()

        updates = []
        current_ver = None

        for line in content.splitlines():
            if line.startswith('#') or not current_ver:
                # may be normal comment or new version
                if rgx := re.fullmatch(r'^# v(?P<ver>\d+\.\d+\.\d+)$', line):
                    current_ver = Version.from_str(rgx['ver'])

                continue

            # we only need the updates between the
            # previous and new version of the server.
            if prev_version < current_ver <= self.version:
                updates.append(line)
Пример #4
0
    async def get_prev_version() -> Optional[Version]:
        """Get the last launched version of the server."""
        res = await glob.db.fetch(
            'SELECT ver_major, ver_minor, ver_micro '
            'FROM startups ORDER BY datetime DESC LIMIT 1',
            _dict=False  # get tuple
        )

        if res:
            return Version(*map(int, res))
Пример #5
0
    async def _update_cmyui(self) -> None:
        """Check if cmyui_pkg has a newer release; update if available."""
        module_ver = Version.from_str(pkg_version('cmyui'))
        latest_ver = await self._get_latest_cmyui()

        if module_ver < latest_ver:
            # package is not up to date; update it.
            log(f'Updating cmyui_pkg (v{module_ver!r} -> '
                                    f'v{latest_ver!r}).', Ansi.MAGENTA)
            pip_main(['install', '-Uq', 'cmyui']) # Update quiet
Пример #6
0
    async def _get_latest_cmyui(self) -> Version:
        """Get the latest version release of cmyui_pkg from pypi."""
        url = 'https://pypi.org/pypi/cmyui/json'
        async with glob.http.get(url) as resp:
            if not resp or resp.status != 200:
                return self.version

            # safe cuz py>=3.7 dicts are ordered
            if not (json := await resp.json()):
                return self.version

            # return most recent release version
            return Version.from_str(list(json['releases'])[-1])
Пример #7
0
from objects import glob

__all__ = ()

"""
app - our quart app pertaining to gulag-web.
"""
app = Quart(__name__)



"""
app version - current version of gulag-web.
"""
version = Version(0, 1, 0)



"""
secret key - used to secure session data.
the only semi-sensitive data we store in
the session is a user's email address.
i recommend using a 2048 character randomly
generated string that excludes escape characters.
"""
app.secret_key = glob.config.secret_key



"""
Пример #8
0
import pyfiglet
import bcrypt
import uuid
import time
import queue

# internal imports
from objects import glob # glob = global, server-wide objects will be stored here e.g database handler
from constants.countries import country_codes
from constants.types import osuTypes
import packets
from packets import BanchoPacketReader, BanchoPacket, Packets

app = Quart(__name__) # handler for webserver :D
glob.db = AsyncSQLPool() # define db globally
glob.version = Version(0, 0, 8) # set Asahi version, mainly for future updater but also for tracking
glob.packets = {}
glob.queue = queue.SimpleQueue()

def enqueue(b: bytes):
    glob.queue.put_nowait(b)

def dequeue():
    try:
        return glob.queue.get_nowait()
    except queue.Empty:
        pass

def queue_empty():
    return glob.queue.empty()