This commit is contained in:
commit
279b2a7e90
49 files changed
+2664
No files matched your search
@@ -0,0 +1,23 @@
|
||||
name: Build and Push Docker Image
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
|
||||
jobs:
|
||||
build-and-push:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Log in to private registry
|
||||
run: echo "${{ secrets.REGISTRY_PASSWORD }}" | docker login registry.ciomek.pl/loonmc-backend:latest -u "${{ secrets.REGISTRY_USERNAME }}" --password-stdin
|
||||
|
||||
- name: Build Docker image
|
||||
run: docker build -t registry.ciomek.pl/loonmc-backend:latest .
|
||||
|
||||
- name: Push Docker image
|
||||
run: docker push registry.ciomek.pl/loonmc-backend:latest
|
||||
+186
@@ -0,0 +1,186 @@
|
||||
.secrets.toml
|
||||
db.sqlite3
|
||||
.idea
|
||||
|
||||
# Created by https://www.toptal.com/developers/gitignore/api/python
|
||||
# Edit at https://www.toptal.com/developers/gitignore?templates=python
|
||||
|
||||
### Python ###
|
||||
# Byte-compiled / optimized / DLL files
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
|
||||
# C extensions
|
||||
*.so
|
||||
|
||||
# Distribution / packaging
|
||||
.Python
|
||||
build/
|
||||
develop-eggs/
|
||||
dist/
|
||||
downloads/
|
||||
eggs/
|
||||
.eggs/
|
||||
lib/
|
||||
lib64/
|
||||
parts/
|
||||
sdist/
|
||||
var/
|
||||
wheels/
|
||||
share/python-wheels/
|
||||
*.egg-info/
|
||||
.installed.cfg
|
||||
*.egg
|
||||
MANIFEST
|
||||
|
||||
# PyInstaller
|
||||
# Usually these files are written by a python script from a template
|
||||
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
||||
*.manifest
|
||||
*.spec
|
||||
|
||||
# Installer logs
|
||||
pip-log.txt
|
||||
pip-delete-this-directory.txt
|
||||
|
||||
# Unit test / coverage reports
|
||||
htmlcov/
|
||||
.tox/
|
||||
.nox/
|
||||
.coverage
|
||||
.coverage.*
|
||||
.cache
|
||||
nosetests.xml
|
||||
coverage.xml
|
||||
*.cover
|
||||
*.py,cover
|
||||
.hypothesis/
|
||||
.pytest_cache/
|
||||
cover/
|
||||
|
||||
# Translations
|
||||
*.mo
|
||||
*.pot
|
||||
|
||||
# Django stuff:
|
||||
*.log
|
||||
local_settings.py
|
||||
db.sqlite3
|
||||
db.sqlite3-journal
|
||||
|
||||
# Flask stuff:
|
||||
instance/
|
||||
.webassets-cache
|
||||
|
||||
# Scrapy stuff:
|
||||
.scrapy
|
||||
|
||||
# Sphinx documentation
|
||||
docs/_build/
|
||||
|
||||
# PyBuilder
|
||||
.pybuilder/
|
||||
target/
|
||||
|
||||
# Jupyter Notebook
|
||||
.ipynb_checkpoints
|
||||
|
||||
# IPython
|
||||
profile_default/
|
||||
ipython_config.py
|
||||
|
||||
# pyenv
|
||||
# For a library or package, you might want to ignore these files since the code is
|
||||
# intended to run in multiple environments; otherwise, check them in:
|
||||
# .python-version
|
||||
|
||||
# pipenv
|
||||
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
||||
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
||||
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
||||
# install all needed dependencies.
|
||||
#Pipfile.lock
|
||||
|
||||
# poetry
|
||||
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
||||
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
||||
# commonly ignored for libraries.
|
||||
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
||||
#poetry.lock
|
||||
|
||||
# pdm
|
||||
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
||||
#pdm.lock
|
||||
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
|
||||
# in version control.
|
||||
# https://pdm.fming.dev/#use-with-ide
|
||||
.pdm.toml
|
||||
|
||||
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
||||
__pypackages__/
|
||||
|
||||
# Celery stuff
|
||||
celerybeat-schedule
|
||||
celerybeat.pid
|
||||
|
||||
# SageMath parsed files
|
||||
*.sage.py
|
||||
|
||||
# Environments
|
||||
.env
|
||||
.venv
|
||||
env/
|
||||
venv/
|
||||
ENV/
|
||||
env.bak/
|
||||
venv.bak/
|
||||
|
||||
# Spyder project settings
|
||||
.spyderproject
|
||||
.spyproject
|
||||
|
||||
# Rope project settings
|
||||
.ropeproject
|
||||
|
||||
# mkdocs documentation
|
||||
/site
|
||||
|
||||
# mypy
|
||||
.mypy_cache/
|
||||
.dmypy.json
|
||||
dmypy.json
|
||||
|
||||
# Pyre type checker
|
||||
.pyre/
|
||||
|
||||
# pytype static type analyzer
|
||||
.pytype/
|
||||
|
||||
# Cython debug symbols
|
||||
cython_debug/
|
||||
|
||||
# PyCharm
|
||||
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
||||
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
||||
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
||||
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
||||
#.idea/
|
||||
|
||||
### Python Patch ###
|
||||
# Poetry local configuration file - https://python-poetry.org/docs/configuration/#local-configuration
|
||||
poetry.toml
|
||||
|
||||
# ruff
|
||||
.ruff_cache/
|
||||
|
||||
# LSP config files
|
||||
pyrightconfig.json
|
||||
|
||||
# End of https://www.toptal.com/developers/gitignore/api/python
|
||||
|
||||
# Ignore dynaconf secret files
|
||||
.secrets.*
|
||||
|
||||
# Allow secrets template to be committed
|
||||
!.secrets.toml.example
|
||||
@@ -0,0 +1 @@
|
||||
3.14
|
||||
@@ -0,0 +1,10 @@
|
||||
[mqtt]
|
||||
host = 'mqtt.host'
|
||||
username = 'loon'
|
||||
password = 'pwd'
|
||||
|
||||
[redis]
|
||||
password = 'pwd'
|
||||
|
||||
[jwt]
|
||||
secret = 'secret'
|
||||
@@ -0,0 +1,8 @@
|
||||
FROM ghcr.io/astral-sh/uv:python3.14-bookworm-slim
|
||||
|
||||
WORKDIR /app
|
||||
COPY . .
|
||||
RUN uv sync --frozen --no-dev
|
||||
|
||||
EXPOSE 8000
|
||||
CMD ["uv", "run", "python", "main.py"]
|
||||
+147
@@ -0,0 +1,147 @@
|
||||
# A generic, single database configuration.
|
||||
|
||||
[alembic]
|
||||
# path to migration scripts.
|
||||
# this is typically a path given in POSIX (e.g. forward slashes)
|
||||
# format, relative to the token %(here)s which refers to the location of this
|
||||
# ini file
|
||||
script_location = %(here)s/alembic
|
||||
|
||||
# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
|
||||
# Uncomment the line below if you want the files to be prepended with date and time
|
||||
# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file
|
||||
# for all available tokens
|
||||
# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s
|
||||
# Or organize into date-based subdirectories (requires recursive_version_locations = true)
|
||||
# file_template = %%(year)d/%%(month).2d/%%(day).2d_%%(hour).2d%%(minute).2d_%%(second).2d_%%(rev)s_%%(slug)s
|
||||
|
||||
# sys.path path, will be prepended to sys.path if present.
|
||||
# defaults to the current working directory. for multiple paths, the path separator
|
||||
# is defined by "path_separator" below.
|
||||
prepend_sys_path = .
|
||||
|
||||
|
||||
# timezone to use when rendering the date within the migration file
|
||||
# as well as the filename.
|
||||
# If specified, requires the tzdata library which can be installed by adding
|
||||
# `alembic[tz]` to the pip requirements.
|
||||
# string value is passed to ZoneInfo()
|
||||
# leave blank for localtime
|
||||
# timezone =
|
||||
|
||||
# max length of characters to apply to the "slug" field
|
||||
# truncate_slug_length = 40
|
||||
|
||||
# set to 'true' to run the environment during
|
||||
# the 'revision' command, regardless of autogenerate
|
||||
# revision_environment = false
|
||||
|
||||
# set to 'true' to allow .pyc and .pyo files without
|
||||
# a source .py file to be detected as revisions in the
|
||||
# versions/ directory
|
||||
# sourceless = false
|
||||
|
||||
# version location specification; This defaults
|
||||
# to <script_location>/versions. When using multiple version
|
||||
# directories, initial revisions must be specified with --version-path.
|
||||
# The path separator used here should be the separator specified by "path_separator"
|
||||
# below.
|
||||
# version_locations = %(here)s/bar:%(here)s/bat:%(here)s/alembic/versions
|
||||
|
||||
# path_separator; This indicates what character is used to split lists of file
|
||||
# paths, including version_locations and prepend_sys_path within configparser
|
||||
# files such as alembic.ini.
|
||||
# The default rendered in new alembic.ini files is "os", which uses os.pathsep
|
||||
# to provide os-dependent path splitting.
|
||||
#
|
||||
# Note that in order to support legacy alembic.ini files, this default does NOT
|
||||
# take place if path_separator is not present in alembic.ini. If this
|
||||
# option is omitted entirely, fallback logic is as follows:
|
||||
#
|
||||
# 1. Parsing of the version_locations option falls back to using the legacy
|
||||
# "version_path_separator" key, which if absent then falls back to the legacy
|
||||
# behavior of splitting on spaces and/or commas.
|
||||
# 2. Parsing of the prepend_sys_path option falls back to the legacy
|
||||
# behavior of splitting on spaces, commas, or colons.
|
||||
#
|
||||
# Valid values for path_separator are:
|
||||
#
|
||||
# path_separator = :
|
||||
# path_separator = ;
|
||||
# path_separator = space
|
||||
# path_separator = newline
|
||||
#
|
||||
# Use os.pathsep. Default configuration used for new projects.
|
||||
path_separator = os
|
||||
|
||||
# set to 'true' to search source files recursively
|
||||
# in each "version_locations" directory
|
||||
# new in Alembic version 1.10
|
||||
# recursive_version_locations = false
|
||||
|
||||
# the output encoding used when revision files
|
||||
# are written from script.py.mako
|
||||
# output_encoding = utf-8
|
||||
|
||||
# database URL is set from Dynaconf (settings.database.url) in alembic/env.py
|
||||
# sqlalchemy.url = driver://user:pass@localhost/dbname
|
||||
|
||||
|
||||
[post_write_hooks]
|
||||
# post_write_hooks defines scripts or Python functions that are run
|
||||
# on newly generated revision scripts. See the documentation for further
|
||||
# detail and examples
|
||||
|
||||
# format using "black" - use the console_scripts runner, against the "black" entrypoint
|
||||
# hooks = black
|
||||
# black.type = console_scripts
|
||||
# black.entrypoint = black
|
||||
# black.options = -l 79 REVISION_SCRIPT_FILENAME
|
||||
|
||||
# lint with attempts to fix using "ruff" - use the module runner, against the "ruff" module
|
||||
# hooks = ruff
|
||||
# ruff.type = module
|
||||
# ruff.module = ruff
|
||||
# ruff.options = check --fix REVISION_SCRIPT_FILENAME
|
||||
|
||||
# Alternatively, use the exec runner to execute a binary found on your PATH
|
||||
# hooks = ruff
|
||||
# ruff.type = exec
|
||||
# ruff.executable = ruff
|
||||
# ruff.options = check --fix REVISION_SCRIPT_FILENAME
|
||||
|
||||
# Logging configuration. This is also consumed by the user-maintained
|
||||
# env.py script only.
|
||||
[loggers]
|
||||
keys = root,sqlalchemy,alembic
|
||||
|
||||
[handlers]
|
||||
keys = console
|
||||
|
||||
[formatters]
|
||||
keys = generic
|
||||
|
||||
[logger_root]
|
||||
level = WARNING
|
||||
handlers = console
|
||||
qualname =
|
||||
|
||||
[logger_sqlalchemy]
|
||||
level = WARNING
|
||||
handlers =
|
||||
qualname = sqlalchemy.engine
|
||||
|
||||
[logger_alembic]
|
||||
level = INFO
|
||||
handlers =
|
||||
qualname = alembic
|
||||
|
||||
[handler_console]
|
||||
class = StreamHandler
|
||||
args = (sys.stderr,)
|
||||
level = NOTSET
|
||||
formatter = generic
|
||||
|
||||
[formatter_generic]
|
||||
format = %(levelname)-5.5s [%(name)s] %(message)s
|
||||
datefmt = %H:%M:%S
|
||||
@@ -0,0 +1 @@
|
||||
Generic single-database configuration.
|
||||
@@ -0,0 +1,80 @@
|
||||
from logging.config import fileConfig
|
||||
|
||||
from sqlalchemy import engine_from_config
|
||||
from sqlalchemy import pool
|
||||
|
||||
from alembic import context
|
||||
from sqlmodel import SQLModel
|
||||
|
||||
from loon.web.db import database_url
|
||||
|
||||
import loon.web
|
||||
|
||||
# this is the Alembic Config object, which provides
|
||||
# access to the values within the .ini file in use.
|
||||
config = context.config
|
||||
|
||||
# Interpret the config file for Python logging.
|
||||
# This line sets up loggers basically.
|
||||
if config.config_file_name is not None:
|
||||
fileConfig(config.config_file_name)
|
||||
|
||||
# add your model's MetaData object here
|
||||
# for 'autogenerate' support
|
||||
# from myapp import mymodel
|
||||
# target_metadata = mymodel.Base.metadata
|
||||
target_metadata = SQLModel.metadata
|
||||
|
||||
config.set_main_option("sqlalchemy.url", database_url())
|
||||
|
||||
|
||||
def run_migrations_offline() -> None:
|
||||
"""Run migrations in 'offline' mode.
|
||||
|
||||
This configures the context with just a URL
|
||||
and not an Engine, though an Engine is acceptable
|
||||
here as well. By skipping the Engine creation
|
||||
we don't even need a DBAPI to be available.
|
||||
|
||||
Calls to context.execute() here emit the given string to the
|
||||
script output.
|
||||
|
||||
"""
|
||||
url = config.get_main_option("sqlalchemy.url")
|
||||
context.configure(
|
||||
url=url,
|
||||
target_metadata=target_metadata,
|
||||
literal_binds=True,
|
||||
dialect_opts={"paramstyle": "named"},
|
||||
)
|
||||
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
def run_migrations_online() -> None:
|
||||
"""Run migrations in 'online' mode.
|
||||
|
||||
In this scenario we need to create an Engine
|
||||
and associate a connection with the context.
|
||||
|
||||
"""
|
||||
connectable = engine_from_config(
|
||||
config.get_section(config.config_ini_section, {}),
|
||||
prefix="sqlalchemy.",
|
||||
poolclass=pool.NullPool,
|
||||
)
|
||||
|
||||
with connectable.connect() as connection:
|
||||
context.configure(
|
||||
connection=connection, target_metadata=target_metadata
|
||||
)
|
||||
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
if context.is_offline_mode():
|
||||
run_migrations_offline()
|
||||
else:
|
||||
run_migrations_online()
|
||||
@@ -0,0 +1,29 @@
|
||||
"""${message}
|
||||
|
||||
Revision ID: ${up_revision}
|
||||
Revises: ${down_revision | comma,n}
|
||||
Create Date: ${create_date}
|
||||
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
${imports if imports else ""}
|
||||
import sqlmodel
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = ${repr(up_revision)}
|
||||
down_revision: Union[str, Sequence[str], None] = ${repr(down_revision)}
|
||||
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
|
||||
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""Upgrade schema."""
|
||||
${upgrades if upgrades else "pass"}
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""Downgrade schema."""
|
||||
${downgrades if downgrades else "pass"}
|
||||
@@ -0,0 +1,41 @@
|
||||
"""Users
|
||||
|
||||
Revision ID: 493f3f7529f3
|
||||
Revises:
|
||||
Create Date: 2026-08-16 11:22:34.176552
|
||||
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
import sqlmodel
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = '493f3f7529f3'
|
||||
down_revision: Union[str, Sequence[str], None] = None
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""Upgrade schema."""
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.create_table('user',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('uuid', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
|
||||
sa.Column('internal_username', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
|
||||
sa.Column('password', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
|
||||
sa.Column('admin', sa.Boolean(), nullable=False),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
sa.UniqueConstraint('uuid')
|
||||
)
|
||||
# ### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""Downgrade schema."""
|
||||
# ### commands auto generated by Alembic - please adjust! ###
|
||||
op.drop_table('user')
|
||||
# ### end Alembic commands ###
|
||||
@@ -0,0 +1,7 @@
|
||||
from dynaconf import Dynaconf
|
||||
|
||||
settings = Dynaconf(
|
||||
envvar_prefix="LOON",
|
||||
settings_files=['settings.toml', '.secrets.toml'],
|
||||
merge_enabled=True,
|
||||
)
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
[loggers]
|
||||
keys = root, uvicorn, uvicorn_error, uvicorn_access, loon
|
||||
|
||||
[handlers]
|
||||
keys = default, access
|
||||
|
||||
[formatters]
|
||||
keys = default, access
|
||||
|
||||
[logger_root]
|
||||
level = INFO
|
||||
handlers = default
|
||||
|
||||
[logger_uvicorn]
|
||||
level = INFO
|
||||
handlers = default
|
||||
propagate = 0
|
||||
qualname = uvicorn
|
||||
|
||||
[logger_uvicorn_error]
|
||||
level = INFO
|
||||
handlers =
|
||||
propagate = 1
|
||||
qualname = uvicorn.error
|
||||
|
||||
[logger_uvicorn_access]
|
||||
level = INFO
|
||||
handlers = access
|
||||
propagate = 0
|
||||
qualname = uvicorn.access
|
||||
|
||||
[logger_loon]
|
||||
level = INFO
|
||||
handlers = default
|
||||
propagate = 0
|
||||
qualname = loon
|
||||
|
||||
[handler_default]
|
||||
class = StreamHandler
|
||||
level = INFO
|
||||
formatter = default
|
||||
args = (sys.stderr,)
|
||||
|
||||
[handler_access]
|
||||
class = StreamHandler
|
||||
level = INFO
|
||||
formatter = access
|
||||
args = (sys.stdout,)
|
||||
|
||||
[formatter_default]
|
||||
format = %(asctime)s [%(levelname)s] %(message)s
|
||||
|
||||
[formatter_access]
|
||||
class = uvicorn.logging.AccessFormatter
|
||||
format = %(asctime)s [%(levelname)s] %(client_addr)s - "%(request_line)s" %(status_code)s
|
||||
@@ -0,0 +1,3 @@
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger("loon")
|
||||
Whitespace-only changes.
Whitespace-only changes.
@@ -0,0 +1,35 @@
|
||||
import json
|
||||
|
||||
from sqlmodel import Session, select
|
||||
|
||||
from loon.web.db import engine
|
||||
from loon.web.users.models import User
|
||||
from loon.web.utils.password import hash_password
|
||||
|
||||
|
||||
async def change_password_handler(client, userdata, msg):
|
||||
data = json.loads(msg.payload.decode())
|
||||
|
||||
if msg.topic != "loon/register/change_password":
|
||||
return
|
||||
|
||||
uuid = data["uuid"]
|
||||
password = data["password"]
|
||||
|
||||
with Session(engine) as session:
|
||||
statement = select(User).where(User.uuid == uuid)
|
||||
user = session.exec(statement).first()
|
||||
|
||||
if user is None:
|
||||
client.publish(f"loon/register/{uuid}/response",
|
||||
json.dumps({"success": False, "error": "The user is not registered!"}))
|
||||
return
|
||||
|
||||
with Session(engine) as session:
|
||||
user = session.exec(
|
||||
select(User).where(User.uuid == uuid)
|
||||
).first()
|
||||
user.password = hash_password(password)
|
||||
session.commit()
|
||||
|
||||
client.publish(f"loon/register/{uuid}/response", json.dumps({"success": True, "error": None}))
|
||||
@@ -0,0 +1,105 @@
|
||||
import json
|
||||
import random
|
||||
|
||||
from loon.web.users.state import user_threads
|
||||
|
||||
PLAYER_EVENT_SUFFIXES = ("died", "joined", "left")
|
||||
|
||||
DEATH_BY_DAMAGE = {
|
||||
"fall": (
|
||||
"{username} fell from a high place",
|
||||
"{username} forgot to tie their shoes",
|
||||
),
|
||||
"fire": (
|
||||
"{username} forgot fire burns",
|
||||
"{username} was engulfed in flames",
|
||||
),
|
||||
"drown": (
|
||||
"{username} drowned",
|
||||
),
|
||||
"blast": (
|
||||
"{username} blew up",
|
||||
),
|
||||
"combat": (
|
||||
"{username} was slain",
|
||||
"{username} was pummeled to death",
|
||||
),
|
||||
"generic": (
|
||||
"{username} died",
|
||||
"{username} withered away",
|
||||
),
|
||||
}
|
||||
|
||||
DEATH_BY_KILLER = {
|
||||
"fall": (
|
||||
"{username} was doomed to fall by {killer}",
|
||||
),
|
||||
"fire": (
|
||||
"{username} walked into fire whilst fighting {killer}",
|
||||
),
|
||||
"drown": (
|
||||
"{username} drowned whilst trying to escape {killer}",
|
||||
),
|
||||
"blast": (
|
||||
"{username} was blown up by {killer}",
|
||||
),
|
||||
"combat": (
|
||||
"{username} was slain by {killer}",
|
||||
"{username} was killed by {killer}",
|
||||
"{username} was slain by {killer} using magic",
|
||||
"{username} got finished off by {killer}",
|
||||
),
|
||||
"generic": (
|
||||
"{username} was slain by {killer}",
|
||||
"{username} was killed by {killer}",
|
||||
),
|
||||
}
|
||||
|
||||
DEATH_BY_KILLER_DEFAULT = DEATH_BY_KILLER["combat"]
|
||||
|
||||
|
||||
def get_random(templates, **kwargs):
|
||||
return random.choice(templates).format(**kwargs)
|
||||
|
||||
|
||||
async def marquee_handler(client, userdata, msg):
|
||||
prefix = "loon/player/"
|
||||
|
||||
if not msg.topic.startswith(prefix):
|
||||
return
|
||||
|
||||
rest = msg.topic[len(prefix):]
|
||||
_, _, subtopic = rest.partition("/")
|
||||
|
||||
if subtopic not in PLAYER_EVENT_SUFFIXES:
|
||||
return
|
||||
|
||||
try:
|
||||
data = json.loads(msg.payload.decode())
|
||||
except json.JSONDecodeError:
|
||||
return
|
||||
|
||||
username = data["player"]["username"]
|
||||
|
||||
if subtopic == "died":
|
||||
killer = data.get("killer")
|
||||
damage_type = data.get("damageType")
|
||||
|
||||
if killer:
|
||||
templates = DEATH_BY_KILLER.get(damage_type, DEATH_BY_KILLER_DEFAULT)
|
||||
message = get_random(templates, username=username, killer=killer)
|
||||
elif damage_type in DEATH_BY_DAMAGE:
|
||||
message = get_random(DEATH_BY_DAMAGE[damage_type], username=username)
|
||||
elif damage_type:
|
||||
message = f"{username} died of {damage_type}"
|
||||
else:
|
||||
message = f"{username} died"
|
||||
elif subtopic == "joined":
|
||||
message = f"{username} joined the game"
|
||||
else:
|
||||
message = f"{username} left the game"
|
||||
|
||||
envelope = json.dumps({"topic": "server/marquee", "payload": {"message": message}})
|
||||
|
||||
for queue in list(user_threads.values()):
|
||||
await queue.put(envelope)
|
||||
@@ -0,0 +1,19 @@
|
||||
import json
|
||||
|
||||
from loon.web.users.state import user_threads
|
||||
|
||||
|
||||
async def player_handler(client, userdata, msg):
|
||||
data = json.loads(msg.payload.decode())
|
||||
|
||||
prefix = "loon/player/"
|
||||
|
||||
if not msg.topic.startswith(prefix):
|
||||
return
|
||||
|
||||
rest = msg.topic[len(prefix):]
|
||||
player_uuid, _, subtopic = rest.partition("/")
|
||||
|
||||
queue = user_threads.get(player_uuid)
|
||||
if queue is not None:
|
||||
await queue.put(json.dumps({"topic": subtopic, "payload": data}))
|
||||
@@ -0,0 +1,34 @@
|
||||
import json
|
||||
|
||||
from sqlmodel import Session, select
|
||||
|
||||
from loon.web.db import engine
|
||||
from loon.web.users.models import User
|
||||
from loon.web.utils.password import hash_password
|
||||
|
||||
|
||||
async def register_request_handler(client, userdata, msg):
|
||||
data = json.loads(msg.payload.decode())
|
||||
|
||||
if msg.topic != "loon/register/request":
|
||||
return
|
||||
|
||||
uuid = data["uuid"]
|
||||
password = data["password"]
|
||||
internal_username = data["internalUsername"]
|
||||
|
||||
with Session(engine) as session:
|
||||
statement = select(User).where(User.uuid == uuid)
|
||||
user = session.exec(statement).first()
|
||||
|
||||
if user is not None:
|
||||
client.publish(f"loon/register/{uuid}/response",
|
||||
json.dumps({"success": False, "error": "The user is already registered!"}))
|
||||
return
|
||||
|
||||
with Session(engine) as session:
|
||||
user = User(uuid=uuid, password=hash_password(password), internal_username=internal_username, admin=False)
|
||||
session.add(user)
|
||||
session.commit()
|
||||
|
||||
client.publish(f"loon/register/{uuid}/response", json.dumps({"success": True, "error": None}))
|
||||
@@ -0,0 +1,18 @@
|
||||
import json
|
||||
|
||||
from loon.web.users.state import user_threads
|
||||
|
||||
|
||||
async def server_handler(client, userdata, msg):
|
||||
if msg.topic != "loon/server/info":
|
||||
return
|
||||
|
||||
try:
|
||||
data = json.loads(msg.payload.decode())
|
||||
except json.JSONDecodeError:
|
||||
return
|
||||
|
||||
envelope = json.dumps({"topic": "server/info", "payload": data})
|
||||
|
||||
for queue in list(user_threads.values()):
|
||||
await queue.put(envelope)
|
||||
@@ -0,0 +1,34 @@
|
||||
import json
|
||||
import re
|
||||
|
||||
import redis
|
||||
|
||||
from config import settings
|
||||
from loon.redis.chunk import set_chunk_cache
|
||||
from loon.web.users.state import user_threads
|
||||
|
||||
|
||||
async def world_handler(client, userdata, msg):
|
||||
chunk_topic = re.compile(r"^loon/world/chunk/(-?\d+)/(-?\d+)$")
|
||||
|
||||
match = chunk_topic.match(msg.topic)
|
||||
|
||||
if not match:
|
||||
return
|
||||
|
||||
try:
|
||||
data = json.loads(msg.payload.decode())
|
||||
except json.JSONDecodeError:
|
||||
return
|
||||
|
||||
x, z = match.group(1), match.group(2)
|
||||
envelope = json.dumps({"topic": f"world/chunk/{x}/{z}", "payload": data})
|
||||
|
||||
if settings.redis.enabled:
|
||||
try:
|
||||
set_chunk_cache(int(x), int(z), data)
|
||||
except redis.RedisError:
|
||||
pass
|
||||
|
||||
for queue in list(user_threads.values()):
|
||||
await queue.put(envelope)
|
||||
@@ -0,0 +1,74 @@
|
||||
import asyncio
|
||||
import json
|
||||
import threading
|
||||
|
||||
import paho.mqtt.client as mqtt
|
||||
|
||||
from config import settings
|
||||
from loon import logger
|
||||
from loon.mqtt.handlers.change_password_request import change_password_handler
|
||||
from loon.mqtt.handlers.marquee import marquee_handler
|
||||
from loon.mqtt.handlers.player import player_handler
|
||||
from loon.mqtt.handlers.register_request import register_request_handler
|
||||
from loon.mqtt.handlers.server import server_handler
|
||||
from loon.mqtt.handlers.world import world_handler
|
||||
|
||||
|
||||
class MQTTManager:
|
||||
BASE_HANDLERS = [player_handler, register_request_handler, world_handler, server_handler, marquee_handler, change_password_handler]
|
||||
|
||||
def __init__(self, inject_handlers = None):
|
||||
if inject_handlers is None:
|
||||
inject_handlers = []
|
||||
|
||||
self.client = mqtt.Client()
|
||||
self.thread = None
|
||||
self.loop = asyncio.get_running_loop()
|
||||
|
||||
self.handlers = self.BASE_HANDLERS + inject_handlers
|
||||
|
||||
@staticmethod
|
||||
def setup_and_start():
|
||||
mqtt_client = MQTTManager()
|
||||
mqtt_client.connect()
|
||||
mqtt_client.start()
|
||||
return mqtt_client
|
||||
|
||||
def connect(self):
|
||||
self.client.on_connect = self.on_connect
|
||||
self.client.on_disconnect = self.on_disconnect
|
||||
self.client.on_message = self.on_topic
|
||||
self.client.username_pw_set(username=settings.mqtt.username, password=settings.mqtt.password)
|
||||
self.client.reconnect_delay_set(min_delay=1, max_delay=60)
|
||||
self.client.connect_async(settings.mqtt.host, settings.mqtt.port)
|
||||
|
||||
def start(self):
|
||||
self.thread = threading.Thread(target=self.client.loop_forever, daemon=True)
|
||||
self.thread.start()
|
||||
return self.thread
|
||||
|
||||
@staticmethod
|
||||
def on_connect(client, userdata, flags, reason_code):
|
||||
logger.info(f"MQTT connected (rc={reason_code})")
|
||||
client.subscribe("loon/#")
|
||||
|
||||
@staticmethod
|
||||
def on_disconnect(client, userdata, reason_code):
|
||||
logger.warning(f"MQTT disconnected (rc={reason_code}). Reconnecting...")
|
||||
|
||||
def on_topic(self, client, userdata, msg):
|
||||
async def handle_message():
|
||||
try:
|
||||
data = json.loads(msg.payload.decode())
|
||||
except json.decoder.JSONDecodeError:
|
||||
return
|
||||
|
||||
logger.info(f"[Received] {data}.")
|
||||
|
||||
for handler in self.handlers:
|
||||
await handler(client, userdata, msg)
|
||||
|
||||
asyncio.run_coroutine_threadsafe(handle_message(), self.loop)
|
||||
|
||||
def publish(self, topic: str, payload: mqtt.PayloadType = None, qos: int = 0, retain: bool = False) -> mqtt.MQTTMessageInfo:
|
||||
return self.client.publish(topic, payload, qos, retain)
|
||||
@@ -0,0 +1,24 @@
|
||||
import redis
|
||||
from redis.backoff import ExponentialBackoff
|
||||
from redis.exceptions import ConnectionError, TimeoutError
|
||||
from redis.retry import Retry
|
||||
|
||||
from config import settings
|
||||
|
||||
r: redis.Redis | None = None
|
||||
if not settings.redis.enabled:
|
||||
r = None
|
||||
else:
|
||||
r = redis.Redis(
|
||||
host=settings.redis.host,
|
||||
port=settings.redis.port,
|
||||
password=settings.redis.password,
|
||||
decode_responses=True,
|
||||
socket_connect_timeout=2,
|
||||
socket_timeout=2,
|
||||
socket_keepalive=True,
|
||||
health_check_interval=30,
|
||||
retry_on_timeout=True,
|
||||
retry=Retry(ExponentialBackoff(cap=10, base=0.5), retries=0),
|
||||
retry_on_error=[ConnectionError, TimeoutError],
|
||||
)
|
||||
@@ -0,0 +1,19 @@
|
||||
import json
|
||||
|
||||
from config import settings
|
||||
from loon.redis import r
|
||||
|
||||
|
||||
def set_chunk_cache(x: int, z: int, chunk_payload):
|
||||
r.setex(f'{x}:{z}', settings.redis.expire_time, str(json.dumps(chunk_payload)))
|
||||
|
||||
def get_chunk_cache(x: int, z: int):
|
||||
chunk = r.get(f'{x}:{z}')
|
||||
|
||||
if chunk:
|
||||
return json.loads(chunk)
|
||||
|
||||
return None
|
||||
|
||||
def reset_chunk_cache(x: int, z: int):
|
||||
return r.delete(f'{x}:{z}')
|
||||
@@ -0,0 +1,47 @@
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
from fastapi import FastAPI
|
||||
from starlette.middleware.authentication import AuthenticationMiddleware
|
||||
from starlette.middleware.cors import CORSMiddleware
|
||||
|
||||
from config import settings
|
||||
from loon.mqtt.manager import MQTTManager
|
||||
from loon.web.auth.middleware import JWTAuthBackend, on_auth_error
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
app.state.mqtt_manager = MQTTManager.setup_and_start()
|
||||
yield
|
||||
|
||||
|
||||
app = FastAPI(lifespan=lifespan)
|
||||
|
||||
app.add_middleware(
|
||||
AuthenticationMiddleware,
|
||||
backend=JWTAuthBackend(),
|
||||
on_error=on_auth_error,
|
||||
)
|
||||
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=settings.web.allowed_origins,
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
|
||||
def get_mqtt_manager() -> MQTTManager:
|
||||
return app.state.mqtt_manager
|
||||
|
||||
from loon.web.auth.router import router as auth_router
|
||||
from loon.web.users.router import router as users_router
|
||||
from loon.web.world.router import router as world_router
|
||||
from loon.web.server.router import router as server_router
|
||||
from loon.web.admin.router import router as admin_router
|
||||
app.include_router(auth_router)
|
||||
app.include_router(users_router)
|
||||
app.include_router(world_router)
|
||||
app.include_router(server_router)
|
||||
app.include_router(admin_router)
|
||||
Whitespace-only changes.
@@ -0,0 +1,25 @@
|
||||
from sqlmodel import Session, select
|
||||
|
||||
from loon.web.db import engine
|
||||
from loon.web.users.models import User
|
||||
|
||||
|
||||
def choose_admin(username: str) -> None:
|
||||
with Session(engine) as session:
|
||||
user = session.exec(
|
||||
select(User).where(User.internal_username == username)
|
||||
).first()
|
||||
|
||||
if user is None:
|
||||
print(f"No user named {username!r}.")
|
||||
return
|
||||
|
||||
if user.admin:
|
||||
print(f"{username} is already admin.")
|
||||
return
|
||||
|
||||
user.admin = True
|
||||
session.add(user)
|
||||
session.commit()
|
||||
|
||||
print(f"Promoted {username} to admin.")
|
||||
@@ -0,0 +1,7 @@
|
||||
from fastapi import APIRouter
|
||||
from starlette.requests import Request
|
||||
|
||||
from loon.web.auth.middleware import admin
|
||||
|
||||
router = APIRouter(prefix="/admin", tags=["admin"])
|
||||
|
||||
Whitespace-only changes.
@@ -0,0 +1,72 @@
|
||||
import jwt
|
||||
from starlette.authentication import (
|
||||
AuthCredentials,
|
||||
AuthenticationBackend,
|
||||
AuthenticationError,
|
||||
BaseUser,
|
||||
requires as _requires,
|
||||
)
|
||||
from starlette.requests import HTTPConnection
|
||||
from starlette.responses import JSONResponse, Response
|
||||
from sqlmodel import Session, select
|
||||
|
||||
from loon.web.db import engine
|
||||
from loon.web.users.models import User
|
||||
from loon.web.utils.jwt import JWT_SECRET, JWT_ALGORITHM
|
||||
|
||||
authenticated = _requires("authenticated", status_code=401)
|
||||
admin = _requires(["authenticated", "admin"], status_code=403)
|
||||
|
||||
|
||||
class AuthenticatedUser(BaseUser):
|
||||
def __init__(self, user: User) -> None:
|
||||
self.user = user
|
||||
|
||||
@property
|
||||
def is_authenticated(self) -> bool:
|
||||
return True
|
||||
|
||||
class JWTAuthBackend(AuthenticationBackend):
|
||||
def _extract_token(self, conn: HTTPConnection) -> str | None:
|
||||
auth_header = conn.headers.get("Authorization")
|
||||
if auth_header is not None:
|
||||
scheme, _, credentials = auth_header.partition(" ")
|
||||
if scheme.lower() == "bearer" and credentials:
|
||||
return credentials
|
||||
|
||||
# Browser WebSocket APIs cannot set Authorization headers.
|
||||
token = conn.query_params.get("token")
|
||||
return token or None
|
||||
|
||||
async def authenticate(
|
||||
self, conn: HTTPConnection
|
||||
) -> tuple[AuthCredentials, AuthenticatedUser] | None:
|
||||
credentials = self._extract_token(conn)
|
||||
if credentials is None:
|
||||
return None
|
||||
|
||||
try:
|
||||
payload = jwt.decode(credentials, JWT_SECRET, algorithms=[JWT_ALGORITHM])
|
||||
except jwt.InvalidTokenError:
|
||||
raise AuthenticationError("Invalid or expired token")
|
||||
|
||||
user_id = payload.get("user_id")
|
||||
if not isinstance(user_id, int):
|
||||
raise AuthenticationError("Invalid or expired token")
|
||||
|
||||
with Session(engine) as session:
|
||||
user = session.exec(select(User).where(User.id == user_id)).first()
|
||||
|
||||
if user is None:
|
||||
raise AuthenticationError("User not found")
|
||||
|
||||
scopes = ["authenticated"]
|
||||
|
||||
if user.admin:
|
||||
scopes.append("admin")
|
||||
|
||||
return AuthCredentials(scopes), AuthenticatedUser(user)
|
||||
|
||||
|
||||
def on_auth_error(conn: HTTPConnection, exc: Exception) -> Response:
|
||||
return JSONResponse({"detail": str(exc)}, status_code=401)
|
||||
@@ -0,0 +1,26 @@
|
||||
from fastapi import APIRouter, HTTPException, status
|
||||
from sqlmodel import Session, select
|
||||
|
||||
from loon.web.auth.schema import JWTResponse, JWTRequest
|
||||
from loon.web.db import engine
|
||||
from loon.web.users.models import User
|
||||
from loon.web.utils.jwt import generate_token
|
||||
from loon.web.utils.password import verify_password
|
||||
|
||||
router = APIRouter(prefix="/auth", tags=["auth"])
|
||||
|
||||
|
||||
@router.post("/jwt/", response_model=JWTResponse)
|
||||
async def get_jwt(body: JWTRequest) -> JWTResponse:
|
||||
with Session(engine) as session:
|
||||
statement = select(User).where(User.internal_username == body.username)
|
||||
user = session.exec(statement).first()
|
||||
|
||||
if user is None or not verify_password(body.password, user.password):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid username or password",
|
||||
)
|
||||
|
||||
assert user.id is not None
|
||||
return JWTResponse(access_token=generate_token(user.id))
|
||||
@@ -0,0 +1,11 @@
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
class JWTRequest(BaseModel):
|
||||
username: str
|
||||
password: str
|
||||
|
||||
|
||||
class JWTResponse(BaseModel):
|
||||
access_token: str
|
||||
token_type: str = "bearer"
|
||||
@@ -0,0 +1,24 @@
|
||||
from sqlmodel import SQLModel, create_engine
|
||||
|
||||
from config import settings
|
||||
|
||||
|
||||
def database_url(url: str | None = None) -> str:
|
||||
url = url or settings.database.url
|
||||
for src, dst in (
|
||||
("mysql://", "mysql+pymysql://"),
|
||||
("postgres://", "postgresql+psycopg://"),
|
||||
("postgresql://", "postgresql+psycopg://"),
|
||||
):
|
||||
if url.startswith(src):
|
||||
return dst + url.removeprefix(src)
|
||||
return url
|
||||
|
||||
|
||||
url = database_url()
|
||||
kwargs: dict = {}
|
||||
if url.startswith("sqlite"):
|
||||
kwargs["connect_args"] = {"check_same_thread": False}
|
||||
|
||||
engine = create_engine(url, echo=True, **kwargs)
|
||||
SQLModel.metadata.create_all(engine)
|
||||
Whitespace-only changes.
@@ -0,0 +1,13 @@
|
||||
from fastapi import APIRouter, Request
|
||||
|
||||
from loon.web import get_mqtt_manager
|
||||
from loon.web.auth.middleware import authenticated
|
||||
|
||||
router = APIRouter(prefix="/server", tags=["server"])
|
||||
|
||||
|
||||
@router.post("/info/request")
|
||||
@authenticated
|
||||
async def request_server_info(request: Request):
|
||||
get_mqtt_manager().publish("loon/server/info/request")
|
||||
return 200
|
||||
Whitespace-only changes.
@@ -0,0 +1,9 @@
|
||||
from sqlmodel import SQLModel, Field
|
||||
|
||||
|
||||
class User(SQLModel, table=True):
|
||||
id: int = Field(default=None, primary_key=True)
|
||||
uuid: str = Field(unique=True)
|
||||
internal_username: str
|
||||
password: str
|
||||
admin: bool = Field(default=False)
|
||||
@@ -0,0 +1,60 @@
|
||||
import asyncio
|
||||
import threading
|
||||
|
||||
from fastapi import APIRouter, Request
|
||||
from starlette.websockets import WebSocket, WebSocketDisconnect
|
||||
|
||||
from loon.web import get_mqtt_manager
|
||||
from loon.web.auth.middleware import authenticated
|
||||
from loon.web.users.state import user_threads
|
||||
|
||||
router = APIRouter(prefix="/users", tags=["users"])
|
||||
|
||||
|
||||
@router.get("/me")
|
||||
@authenticated
|
||||
async def me(request: Request):
|
||||
return request.user.user.model_dump(exclude={"password", "id"})
|
||||
|
||||
@router.post("/inventory/request")
|
||||
@authenticated
|
||||
async def request_inventory(request: Request):
|
||||
user = request.user.user
|
||||
get_mqtt_manager().publish(f"loon/player/{user.uuid}/inventory/full/request")
|
||||
|
||||
return 200
|
||||
|
||||
@router.post("/online/request")
|
||||
@authenticated
|
||||
async def request_online(request: Request):
|
||||
user = request.user.user
|
||||
get_mqtt_manager().publish(f"loon/player/{user.uuid}/online/request")
|
||||
|
||||
return 200
|
||||
|
||||
@router.post("/position/request")
|
||||
@authenticated
|
||||
async def request_position(request: Request):
|
||||
user = request.user.user
|
||||
get_mqtt_manager().publish(f"loon/player/{user.uuid}/position/request")
|
||||
|
||||
return 200
|
||||
|
||||
|
||||
@router.websocket("/me")
|
||||
@authenticated
|
||||
async def websocket_endpoint(websocket: WebSocket):
|
||||
await websocket.accept()
|
||||
user = websocket.user.user
|
||||
|
||||
queue = asyncio.Queue()
|
||||
user_threads[user.uuid] = queue
|
||||
|
||||
try:
|
||||
while True:
|
||||
message = await queue.get()
|
||||
await websocket.send_text(message)
|
||||
except WebSocketDisconnect:
|
||||
pass
|
||||
finally:
|
||||
user_threads.pop(user.uuid, None)
|
||||
@@ -0,0 +1 @@
|
||||
user_threads = {}
|
||||
Whitespace-only changes.
@@ -0,0 +1,20 @@
|
||||
import time
|
||||
|
||||
import jwt
|
||||
|
||||
from config import settings
|
||||
|
||||
JWT_SECRET = settings.jwt.secret
|
||||
JWT_ALGORITHM = "HS256"
|
||||
|
||||
|
||||
def generate_token(user_id: int) -> str:
|
||||
payload = {
|
||||
"user_id": user_id,
|
||||
"exp": int(time.time()) + 60 * 60 * 24,
|
||||
}
|
||||
return jwt.encode(payload, JWT_SECRET, algorithm=JWT_ALGORITHM)
|
||||
|
||||
def decode_token(token: str) -> dict:
|
||||
payload = jwt.decode(token, JWT_SECRET)
|
||||
return payload
|
||||
@@ -0,0 +1,19 @@
|
||||
from argon2 import PasswordHasher
|
||||
from argon2.exceptions import InvalidHashError, VerifyMismatchError
|
||||
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
ph = PasswordHasher()
|
||||
|
||||
hashed = ph.hash(password)
|
||||
|
||||
return str(hashed)
|
||||
|
||||
|
||||
def verify_password(password: str, hashed_password: str) -> bool:
|
||||
ph = PasswordHasher()
|
||||
|
||||
try:
|
||||
return ph.verify(hashed_password, password)
|
||||
except (VerifyMismatchError, InvalidHashError):
|
||||
return False
|
||||
Whitespace-only changes.
@@ -0,0 +1,80 @@
|
||||
import json
|
||||
|
||||
import redis
|
||||
from fastapi import APIRouter, Request
|
||||
|
||||
from config import settings
|
||||
from loon.redis.chunk import get_chunk_cache, reset_chunk_cache
|
||||
from loon.web import get_mqtt_manager
|
||||
from loon.web.auth.middleware import authenticated
|
||||
from loon.web.users.state import user_threads
|
||||
|
||||
router = APIRouter(prefix="/world", tags=["world"])
|
||||
|
||||
|
||||
@router.get("/request")
|
||||
@authenticated
|
||||
async def request_world(
|
||||
request: Request,
|
||||
x_start: int,
|
||||
x_end: int,
|
||||
z_start: int,
|
||||
z_end: int,
|
||||
):
|
||||
if not settings.redis.enabled:
|
||||
get_mqtt_manager().publish(f"loon/world/chunks/{x_start}:{x_end}/{z_start}:{z_end}/request")
|
||||
return 200
|
||||
|
||||
misses = []
|
||||
thread = user_threads.get(request.user.user.uuid)
|
||||
|
||||
try:
|
||||
for x in range(x_start, x_end + 1):
|
||||
for z in range(z_start, z_end + 1):
|
||||
cached_chunk = get_chunk_cache(x, z)
|
||||
|
||||
if cached_chunk is not None:
|
||||
if thread:
|
||||
await thread.put(
|
||||
json.dumps({"topic": f"world/chunk/{x}/{z}", "payload": cached_chunk})
|
||||
)
|
||||
else:
|
||||
misses.append((x, z))
|
||||
except redis.RedisError as e:
|
||||
get_mqtt_manager().publish(f"loon/world/chunks/{x_start}:{x_end}/{z_start}:{z_end}/request")
|
||||
return 200
|
||||
|
||||
for xa, xb, za, zb in miss_row_rects(misses):
|
||||
get_mqtt_manager().publish(f"loon/world/chunks/{xa}:{xb}/{za}:{zb}/request")
|
||||
|
||||
return 200
|
||||
|
||||
|
||||
def miss_row_rects(misses: list):
|
||||
rows = {}
|
||||
|
||||
for x, z in misses:
|
||||
if z not in rows:
|
||||
rows[z] = []
|
||||
rows[z].append(x)
|
||||
|
||||
rects = []
|
||||
|
||||
for z, xs in rows.items():
|
||||
xs.sort()
|
||||
|
||||
start = xs[0]
|
||||
end = xs[0]
|
||||
|
||||
for x in xs[1:]:
|
||||
if x == end + 1:
|
||||
end = x
|
||||
else:
|
||||
rects.append((start, end, z, z))
|
||||
start = x
|
||||
end = x
|
||||
|
||||
rects.append((start, end, z, z))
|
||||
|
||||
return rects
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
import argparse
|
||||
import uvicorn
|
||||
from pathlib import Path
|
||||
|
||||
from loon.web import app
|
||||
|
||||
LOG_CONFIG = Path(__file__).with_name("logging.ini")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument(
|
||||
"--choose-admin",
|
||||
metavar="USERNAME",
|
||||
help="Promote a user to admin",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.choose_admin is not None:
|
||||
from loon.web.admin.cli import choose_admin
|
||||
|
||||
choose_admin(args.choose_admin)
|
||||
else:
|
||||
uvicorn.run(app, host="0.0.0.0", port=8000, log_config=str(LOG_CONFIG))
|
||||
@@ -0,0 +1,67 @@
|
||||
[project]
|
||||
name = "loon-backend"
|
||||
version = "0.1.0"
|
||||
description = "Add your description here"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.14"
|
||||
dependencies = [
|
||||
"alembic==1.18.5",
|
||||
"annotated-doc==0.0.5",
|
||||
"annotated-types==0.8.0",
|
||||
"anyio==4.14.2",
|
||||
"argon2-cffi==25.1.0",
|
||||
"argon2-cffi-bindings==25.1.0",
|
||||
"certifi==2026.7.22",
|
||||
"cffi==2.1.0",
|
||||
"click==8.4.2",
|
||||
"detect-installer==0.1.0",
|
||||
"dnspython==2.8.0",
|
||||
"dynaconf==3.3.4",
|
||||
"email-validator==2.3.0",
|
||||
"fastapi==0.141.1",
|
||||
"fastapi-cli==0.0.32",
|
||||
"fastapi-cloud-cli==0.23.0",
|
||||
"fastar==0.11.0",
|
||||
"greenlet==3.5.4",
|
||||
"h11==0.16.0",
|
||||
"httpcore==1.0.9",
|
||||
"httptools==0.8.0",
|
||||
"httpx==0.28.1",
|
||||
"idna==3.18",
|
||||
"jinja2==3.1.6",
|
||||
"mako==1.3.12",
|
||||
"markdown-it-py==4.2.0",
|
||||
"markupsafe==3.0.3",
|
||||
"mdurl==0.1.2",
|
||||
"paho-mqtt==2.1.0",
|
||||
"psycopg[binary]>=3.3.4",
|
||||
"pycparser==3.0",
|
||||
"pydantic==2.13.4",
|
||||
"pydantic-core==2.46.4",
|
||||
"pydantic-extra-types==2.11.1",
|
||||
"pydantic-settings==2.14.2",
|
||||
"pygments==2.20.0",
|
||||
"pyjwt==2.13.0",
|
||||
"pymysql>=1.2.0",
|
||||
"python-decouple==3.8",
|
||||
"python-dotenv==1.2.2",
|
||||
"python-multipart==0.0.32",
|
||||
"pyyaml==6.0.3",
|
||||
"redis>=8.1.0",
|
||||
"rich==15.0.0",
|
||||
"rich-toolkit==0.20.3",
|
||||
"rignore==0.8.0",
|
||||
"sentry-sdk==2.66.1",
|
||||
"shellingham==1.5.4",
|
||||
"sqlalchemy==2.0.51",
|
||||
"sqlmodel==0.0.39",
|
||||
"starlette==1.3.1",
|
||||
"typer==0.27.0",
|
||||
"typing-extensions==4.16.0",
|
||||
"typing-inspection==0.4.2",
|
||||
"urllib3==2.7.0",
|
||||
"uvicorn==0.52.1",
|
||||
"uvloop==0.22.1",
|
||||
"watchfiles==1.2.0",
|
||||
"websockets==17.0.1",
|
||||
]
|
||||
@@ -0,0 +1,13 @@
|
||||
[web]
|
||||
allowed_origins = ["http://localhost:5173"]
|
||||
|
||||
[redis]
|
||||
host = 'localhost'
|
||||
port = 6379
|
||||
expire_time = 600 # 10 minutes
|
||||
|
||||
[database]
|
||||
url = 'sqlite:///db.sqlite3'
|
||||
|
||||
[mqtt]
|
||||
port = 1883
|
||||
Reference in new issue
Block a user