maubot/maubot/server.py

64 lines
2.3 KiB
Python
Raw Normal View History

2018-10-16 13:41:02 +00:00
# maubot - A plugin-based Matrix bot system.
# Copyright (C) 2018 Tulir Asokan
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
from aiohttp import web
import logging
2018-10-16 13:41:02 +00:00
import asyncio
2018-10-16 19:15:35 +00:00
from mautrix.api import PathBuilder, Method
2018-10-16 13:41:02 +00:00
from .config import Config
from .__meta__ import __version__
class MaubotServer:
log: logging.Logger = logging.getLogger("maubot.server")
def __init__(self, config: Config, management: web.Application,
loop: asyncio.AbstractEventLoop) -> None:
2018-10-16 13:41:02 +00:00
self.loop = loop or asyncio.get_event_loop()
self.app = web.Application(loop=self.loop)
self.config = config
path = PathBuilder(config["server.base_path"])
2018-10-16 19:15:35 +00:00
self.add_route(Method.GET, path.version, self.version)
self.app.add_subapp(config["server.base_path"], management)
2018-10-16 13:41:02 +00:00
as_path = PathBuilder(config["server.appservice_base_path"])
2018-10-16 19:15:35 +00:00
self.add_route(Method.PUT, as_path.transactions, self.handle_transaction)
2018-10-16 13:41:02 +00:00
self.runner = web.AppRunner(self.app)
2018-10-16 19:15:35 +00:00
def add_route(self, method: Method, path: PathBuilder, handler) -> None:
self.app.router.add_route(method.value, str(path), handler)
2018-10-16 13:41:02 +00:00
async def start(self) -> None:
await self.runner.setup()
site = web.TCPSite(self.runner, self.config["server.hostname"], self.config["server.port"])
await site.start()
self.log.info(f"Listening on {site.name}")
2018-10-16 13:41:02 +00:00
async def stop(self) -> None:
await self.runner.cleanup()
@staticmethod
async def version(_: web.Request) -> web.Response:
return web.json_response({
"version": __version__
})
async def handle_transaction(self, request: web.Request) -> web.Response:
return web.Response(status=501)