コード例 #1
0
from mautrix.util.async_db import UpgradeTable

upgrade_table = UpgradeTable()

from . import initial_revision
コード例 #2
0
# Copyright (c) 2022 Tulir Asokan
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from __future__ import annotations

import logging

from mautrix.util.async_db import Connection, Scheme, UpgradeTable

upgrade_table = UpgradeTable(
    version_table_name="crypto_version",
    database_name="crypto store",
    log=logging.getLogger("mau.crypto.db.upgrade"),
)


@upgrade_table.register(description="Latest revision", upgrades_to=4)
async def upgrade_blank_to_v4(conn: Connection) -> None:
    await conn.execute("""CREATE TABLE IF NOT EXISTS crypto_account (
            account_id TEXT PRIMARY KEY,
            device_id  TEXT,
            shared     BOOLEAN      NOT NULL,
            sync_token TEXT         NOT NULL,
            account    bytea        NOT NULL
        )""")
    await conn.execute("""CREATE TABLE IF NOT EXISTS crypto_message_index (
            sender_key CHAR(43),
            session_id CHAR(43),
            "index"    INTEGER,
コード例 #3
0
ファイル: upgrade.py プロジェクト: tulir/mautrix-python
# Copyright (c) 2022 Tulir Asokan
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import logging

from mautrix.util.async_db import Connection, Scheme, UpgradeTable

upgrade_table = UpgradeTable(
    version_table_name="mx_version",
    database_name="matrix state cache",
    log=logging.getLogger("mau.client.db.upgrade"),
)


@upgrade_table.register(description="Latest revision", upgrades_to=2)
async def upgrade_blank_to_v2(conn: Connection, scheme: Scheme) -> None:
    await conn.execute(
        """CREATE TABLE mx_room_state (
            room_id              TEXT PRIMARY KEY,
            is_encrypted         BOOLEAN,
            has_full_member_list BOOLEAN,
            encryption           TEXT,
            power_levels         TEXT
        )"""
    )
    membership_check = ""
    if scheme != Scheme.SQLITE:
        await conn.execute(
            "CREATE TYPE membership AS ENUM ('join', 'leave', 'invite', 'ban', 'knock')"
コード例 #4
0
async def sappservice(config_filename, loop):
    config = Config(config_filename, "", "")
    config.load()

    logging.config.dictConfig(copy.deepcopy(config["logging"]))

    log: logging.Logger = logging.getLogger("sappservice")

    log.info("Initializing matrix spring lobby appservice")
    log.info(f"Config file: {config_filename}")

    # def exception_hook(etype, value, trace):
    #     log.debug(traceback.format_exception(etype, value, trace))
    #
    # sys.excepthook = exception_hook

    ################
    #
    # Initialization
    #
    ################

    mebibyte = 1024**2

    server = config["homeserver.address"]
    domain = config["homeserver.domain"]
    verify_ssl = config["homeserver.verify_ssl"]

    as_token = config["appservice.as_token"]
    hs_token = config["appservice.hs_token"]

    bot_localpart = config["appservice.bot_username"]
    max_body_size = config["appservice.max_body_size"]

    hostname = config["appservice.hostname"]
    port = config["appservice.port"]
    client_name = config["spring.client_name"]
    rooms = config["bridge.rooms"]

    upgrade_table = UpgradeTable()

    db = PostgresDatabase(config["appservice.database"], upgrade_table)
    await db.start()

    state_store_db = PgASStateStore(db=db)
    await state_store_db.upgrade_table.upgrade(db.pool)

    appserv = AppService(
        server=server,
        domain=domain,
        verify_ssl=verify_ssl,
        as_token=as_token,
        hs_token=hs_token,
        bot_localpart=bot_localpart,
        loop=loop,
        id='appservice',
        state_store=state_store_db,
        aiohttp_params={"client_max_size": max_body_size * mebibyte})

    spring_lobby_client = SpringLobbyClient(appserv, config, loop=loop)

    await db.start()
    await appserv.start(hostname, port)
    await spring_lobby_client.start()

    ################
    #
    # Lobby events
    #
    ################

    @spring_lobby_client.bot.on("tasserver")
    async def on_lobby_tasserver(message):
        log.debug(f"on_lobby_tasserver {message}")
        if message.client.name == client_name:
            message.client._login()

    @spring_lobby_client.bot.on("clients")
    async def on_lobby_clients(message):
        log.debug(f"on_lobby_clients {message}")
        if message.client.name != client_name:
            channel = message.params[0]
            clients = message.params[1:]
            await spring_lobby_client.join_matrix_room(channel, clients)

    @spring_lobby_client.bot.on("joined")
    async def on_lobby_joined(message, user, channel):
        log.debug(f"LOBBY JOINED user: {user.username} room: {channel}")
        if user.username != "appservice":
            await spring_lobby_client.join_matrix_room(channel,
                                                       [user.username])

    @spring_lobby_client.bot.on("left")
    async def on_lobby_left(message, user, channel):
        log.debug(f"LOBBY LEFT user: {user.username} room: {channel}")

        if channel.startswith("__battle__"):
            return

        if user.username == "appservice":
            return

        await spring_lobby_client.leave_matrix_room(channel, [user.username])

    @spring_lobby_client.bot.on("said")
    async def on_lobby_said(message, user, target, text):
        if message.client.name == client_name:
            await spring_lobby_client.said(user, target, text)

    @spring_lobby_client.bot.on("saidex")
    async def on_lobby_saidex(message, user, target, text):
        if message.client.name == client_name:
            await spring_lobby_client.saidex(user, target, text)

    # @spring_lobby_client.bot.on("denied")
    # async def on_lobby_denied(message):
    #     return
    #     # if message.client.name != client_name:
    #     #    user = message.client.name
    #     #    await spring_appservice.register(user)

    # @spring_lobby_client.bot.on("adduser")
    # async def on_lobby_adduser(message):
    #     if message.client.name != client_name:
    #         username = message.params[0]
    #
    #         if username == "ChanServ":
    #             return
    #         if username == "appservice":
    #             return
    #
    #         await spring_lobby_client.login_matrix_account(username)

    # @spring_lobby_client.bot.on("removeuser")
    # async def on_lobby_removeuser(message):
    #     if message.client.name != client_name:
    #         username = message.params[0]
    #
    #         if username == "ChanServ":
    #             return
    #         if username == "appservice":
    #             return
    #
    #         await spring_lobby_client.logout_matrix_account(username)

    @spring_lobby_client.bot.on("accepted")
    async def on_lobby_accepted(message):
        log.debug(f"message Accepted {message}")
        await spring_lobby_client.config_rooms()
        await spring_lobby_client.sync_matrix_users()

    @spring_lobby_client.bot.on("failed")
    async def on_lobby_failed(message):
        log.debug(f"message FAILED {message}")

    matrix = Matrix(appserv, spring_lobby_client, config)

    appserv.matrix_event_handler(matrix.handle_event)

    await matrix.wait_for_connection()
    await matrix.init_as_bot()

    # appservice_account = await appserv.intent.whoami()
    # user = appserv.intent.user(appservice_account)

    await appserv.intent.set_presence(PresenceState.ONLINE)

    # location = config["homeserver"]["domain"].split(".")[0]
    # external_id = "MatrixAppService"
    # external_username = config["appservice"]["bot_username"].split("_")[1]

    # for room in rooms:
    #
    #     enabled = config["bridge.rooms"][room]["enabled"]
    #     room_id = config["bridge.rooms"][room]["room_id"]
    #     room_alias = f"{config['appservice.namespace']}_{room}"
    #
    #     if enabled is True:
    #         await user.ensure_joined(room_id=room_id)
    #         await appserv.intent.add_room_alias(room_id=RoomID(room_id), alias_localpart=room_alias, override=True)
    #     # else:
    #     #     # await appserv.intent.remove_room_alias(alias_localpart=room_alias)
    #     #     try:
    #     #         await user.leave_room(room_id=room_id)
    #     #     except Exception as e:
    #     #         log.debug(f"Failed to leave room, not previously joined: {e}")

    appserv.ready = True
    log.info("Initialization complete, running startup actions")

    for signame in ('SIGINT', 'SIGTERM'):
        loop.add_signal_handler(
            getattr(signal, signame),
            lambda: asyncio.ensure_future(spring_lobby_client.exit(signame)))