Beispiel #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
Beispiel #2
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))
Beispiel #3
0
    async def _update_cmyui(self) -> None:
        """Check if cmyui_pkg has a newer release; update if available."""
        module_ver = Version.from_str(importlib.metadata.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.LMAGENTA)
            pip_main(['install', '-Uq', 'cmyui']) # Update quiet
Beispiel #4
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

            if not (json := await resp.json()):
                return self.version

            # return most recent release version
            return Version.from_str(json['info']['version'])
Beispiel #5
0
from constants.countries import country_codes
from endpoints.assets import assets
from endpoints.assets import init_customs
from objects import glob  # global objects
from objects.achievement import Achievement
from objects.clan import Clan
from objects.tasks import expired_donor
from objects.tasks import freeze_timers
from objects.tasks import prepare_tasks
from utils import housekeeping
from utils.logging import debug
from utils.logging import error
from utils.logging import info

glob.version = Version(0, 4, 3)  # TODO: autoupdater using this

glob.app = Xevel(glob.config.socket, gzip=4)  # webserver
dc = commands.Bot(command_prefix=glob.config.bot_prefix)

os.chdir(os.path.dirname(os.path.realpath(__file__)))


@glob.app.before_serving()
async def connect(
) -> None:  # ran before server startup, used to do things like connecting to mysql :D
    info(f"Asahi v{glob.version} starting")

    glob.web = ClientSession()  # aiohttp session for external web requests

    from lists.players import PlayerList
Beispiel #6
0
from quart import Quart
from quart import render_template

from cmyui.logging import Ansi
from cmyui.logging import log
from cmyui.version import Version

from fatFuckSQL import fatFawkSQL

from objects import glob

app = Quart(__name__)
app.config["TEMPLATES_AUTO_RELOAD"] = True
app.config["PERMANENT_SESSION_LIFETIME"] = 315400000

version = Version(1, 3, 0)

# used to secure session data.
# we recommend using a long randomly generated ascii string.
app.secret_key = glob.config.secret_key


@app.before_serving
async def mysql_conn() -> None:
    glob.db = await fatFawkSQL.connect(**glob.config.mysql)
    log('Connected to MySQL!', Ansi.LGREEN)


@app.before_serving
async def http_conn() -> None:
    glob.http = aiohttp.ClientSession(json_serialize=orjson.dumps)
Beispiel #7
0
from quart import Quart
from quart import render_template

from cmyui.logging import Ansi
from cmyui.logging import log
from cmyui.mysql import AsyncSQLPool
from cmyui.version import Version

from objects import glob

if __name__ != '__main__':
    raise RuntimeError('main.py should be run directly!')

app = Quart(__name__)

version = Version(1, 2, 0)

# used to secure session data.
# we recommend using a long randomly generated ascii string.
app.secret_key = glob.config.secret_key

@app.before_serving
async def mysql_conn() -> None:
    glob.db = AsyncSQLPool()
    await glob.db.connect(glob.config.mysql)
    log('Connected to MySQL!', Ansi.LGREEN)

@app.before_serving
async def http_conn() -> None:
    glob.http = aiohttp.ClientSession(json_serialize=orjson.dumps)
    log('Got our Client Session!', Ansi.LGREEN)
Beispiel #8
0
import config
"""
bot - our discord bot.
bot.start_time - our initial start time of Moé.
"""
bot = Bot(command_prefix=[],
          intents=Intents.all())  # NOTE: no bot prefix - we use slash commands
bot.start_time = datetime.utcnow()
"""
bot.version - current version of Moé.
NOTE:
    - major: breaking changes
    - minor: command changes/new features
    - patch: typo fixes/bug fixes
"""
bot.version = Version(2, 4, 4)
"""
cogs - load all external cogs for Moé.
"""
log("--- Start Cogs ---", Ansi.MAGENTA)
for c in os.listdir("./cogs"):
    filename, ext = os.path.splitext(c)
    try:
        if filename != "__pycache__":
            bot.load_extension(f"cogs.{filename}")
            log(f"Loaded cog: cog.{filename}!", Ansi.LGREEN)
    except Exception as ex:
        log(f"Failed to load cog: cog.{filename}!", Ansi.LRED)
        if config.debug:
            log(f"{ex}", Ansi.LRED)
        continue
Beispiel #9
0
from cmyui.web import TCPServer, Connection
from cmyui.version import Version
from cmyui.mysql import SQLPool

from console import *
from handlers import *

from objects import glob
from objects.player import Player
from objects.channel import Channel
from constants.privileges import Privileges

# Set CWD to /gulag.
chdir(path.dirname(path.realpath(__file__)))

glob.version = Version(1, 5, 2)
glob.db = SQLPool(pool_size=4, **glob.config.mysql)

# Aika
glob.bot = Player(id=1, name='Aika', priv=Privileges.Normal)
glob.bot.ping_time = 0x7fffffff

glob.bot.stats_from_sql_full()  # no need to get friends
glob.players.add(glob.bot)

# Add all channels from db.
for chan in glob.db.fetchall('SELECT * FROM channels'):
    glob.channels.add(Channel(**chan))

serv: TCPServer
conn: Connection