Skip to content

Commit

Permalink
Merge pull request #32 from Mooling0602/dev
Browse files Browse the repository at this point in the history
dev -> main
  • Loading branch information
Mooling0602 authored Jan 1, 2025
2 parents c0be0b6 + a70a945 commit dee1f20
Show file tree
Hide file tree
Showing 20 changed files with 300 additions and 158 deletions.
4 changes: 2 additions & 2 deletions config.ini
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
# Ci configuration for GitHub Actions.
[framework]
ver=4
ver=3
[main]
ver=2.5.0
ver=2.5.1
[release]
test=0
[ci]
Expand Down
6 changes: 5 additions & 1 deletion lang/en_us.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@ matrix_sync:
success: Login by password successfully!
save_token: Saving token for the bot account...
on_receiver_cancelled: Receiver task was cancelled.
on_send_command: Message is sending to matrix...
on_send_command:
sending: Message is sending to matrix...
failed: Error when sending message
on_sync_running: Already running message sync!
on_sync_start: Starting message sync...
on_unload: Unloading MatrixSync...
Expand All @@ -25,6 +27,8 @@ matrix_sync:
on_startup: MC server started!
on_stop: MC server stopped.
on_crash: MC server crashed!
settings_comp_check:
failed: "Compatibility check failed! Backup old settings as \"settings.json.bak\"."
sync_status:
running: MSync is running...
not_running: MSync is not running.
Expand Down
6 changes: 5 additions & 1 deletion lang/zh_cn.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@ matrix_sync:
success: 成功使用密码完成登录!
save_token: 正在为机器人账号保存Token...
on_receiver_cancelled: 接收器任务已经取消。
on_send_command: 消息正在发送到Matrix...
on_send_command:
sending: 消息正在发送到Matrix...
failed: 发送消息时发生错误
on_sync_running: 消息同步已在运行!
on_sync_start: 开始消息同步...
on_unload: 正在卸载 MatrixSync...
Expand All @@ -25,6 +27,8 @@ matrix_sync:
on_startup: MC服务器启动完成!
on_stop: MC服务器已关闭
on_crash: MC服务器发生崩溃!
settings_comp_check:
failed: "兼容性检查失败!旧有的设置项将备份为\"settings.json.bak\""
sync_status:
running: "[MSync] 消息同步正在运行..."
not_running: "[MSync] 消息同步未在运行!"
Expand Down
16 changes: 9 additions & 7 deletions matrix_sync/client/init.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import json
import sys
import aiofiles
import matrix_sync.logger.get_logger as get_logger
import matrix_sync.plg_globals as plg_globals

from . import *
from ..utils.logger import *
from ..utils import configDir, tr
from ..utils.token import getToken
from nio import LoginResponse

Expand All @@ -17,28 +18,29 @@ async def cache_token(resp: LoginResponse):
}))

async def login_by_password():
logger = get_logger()
client = AsyncClient(
get_homeserver(plg_globals.config["homeserver"]),
plg_globals.config["user_id"],
plg_globals.config["device_id"]
)
resp = await client.login(plg_globals.config["password"], device_name=plg_globals.config["device_id"])
if isinstance(resp, LoginResponse):
log_info(tr("login.success"))
logger.info(tr("login.success"), "FirstLogin")
await cache_token(resp)
log_info(tr("login.save_token"))
plg_globals.token_vaild = True
logger.info(tr("login.save_token"), "FirstLogin")
else:
tip = tr("login.failed")
log_error(f"{tip}: {resp}")
logger.error(f"{tip}: {resp}", "FirstLogin")
homeserver = get_homeserver(plg_globals.config["homeserver"])
log_info(f'homeserver: "{homeserver}", bot: "{plg_globals.config["user_id"]}"')
log_error(tr("check_config"))
logger.info(f'homeserver: "{homeserver}", bot: "{plg_globals.config["user_id"]}"', "FirstLogin")
logger.error(tr("check_config"), "FirstLogin")
sys.exit(1)

async def check_token() -> bool:
user, token = await getToken()
if user != plg_globals.config["user_id"]:
log_error(tr("token_mismatch"))
return False
else:
return True
100 changes: 44 additions & 56 deletions matrix_sync/client/receiver.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
# thread MatrixReceiver
import asyncio
import matrix_sync.logger.get_logger as get_logger
import matrix_sync.plg_globals as plg_globals

from . import *
from .init import check_token
from ..utils.logger import *
from ..utils.token import getToken
from ..utils import tr
from ..event import *
Expand All @@ -16,77 +15,66 @@
receiver = None

async def message_callback(room: MatrixRoom, event: RoomMessageText) -> None:
message_format = plg_globals.settings["message_format"]["all_room"]
room_message = message_format.replace('%room_display_name%', room.display_name).replace('%sender%', room.user_name(event.sender)).replace('%message%', event.body)
# Avoid echo messages.
if not event.sender == plg_globals.config["user_id"]:
# Apply settings config
if not plg_globals.settings["listen"]["all_rooms"]:
message_format = plg_globals.settings["message_format"]["single_room"]
room_message = message_format.replace('%sender%', room.user_name(event.sender)).replace('%message%', event.body)
event_dispatcher(MatrixMessageEvent, event.body, room.user_name(event.sender), room.room_id)
log_info(room_message, "Message")
psi.say(room_message)
room_info.id = room.room_id
room_info.display_name= room.display_name
if event.sender != plg_globals.config["user_id"]:
event_dispatcher(MatrixMessageEvent, event.body, room.user_name(event.sender), room)

def on_sync_error(response: SyncError):
logger = get_logger()
global homeserver_online
log_error(f"Sync error: {response.status_code}")
logger.error(f"Sync error: {response.status_code}")
if response.status_code >= 500:
homeserver_online = False

async def get_messages() -> None:
logger = get_logger()
global receiver
resp = None
client = AsyncClient(homeserver=get_homeserver(plg_globals.config["homeserver"]))
token_vaild = await check_token()
if token_vaild:
user, token = await getToken()

client.user_id = plg_globals.config["user_id"]
client.access_token = token
client.device_id = plg_globals.config["device_id"]
client.user_id = plg_globals.config["user_id"]
user, token = await getToken()
client.access_token = token
client.device_id = plg_globals.config["device_id"]

if not plg_globals.settings["listen"]["all_rooms"]:
log_info("ok.")
cfg_room_id = plg_globals.config["room_id"]
log_info(f"Listening: {cfg_room_id}")
resp = await client.upload_filter(room={"rooms": [cfg_room_id]})
if isinstance(resp, UploadFilterError):
log_error(resp)
if not plg_globals.settings["listen"]["all_rooms"]:
logger.info("ok.", "Receiver")
cfg_room_id = plg_globals.config["room_id"]
logger.info(f"Listening: {cfg_room_id}", "Receiver")
resp = await client.upload_filter(room={"rooms": [cfg_room_id]})
if isinstance(resp, UploadFilterError):
logger.error(resp, "Receiver")

client.add_response_callback(on_sync_error, SyncError)
client.add_response_callback(on_sync_error, SyncError)

if homeserver_online:
if plg_globals.settings["listen"]["old_messages"] is True:
receiver = asyncio.create_task(client.sync_forever(timeout=5))
else:
if resp is not None:
await client.sync(timeout=5, sync_filter=resp.filter_id)
client.add_event_callback(message_callback, RoomMessageText)
receiver = asyncio.create_task(client.sync_forever(timeout=5, sync_filter=resp.filter_id))
else:
await client.sync(timeout=5)
client.add_event_callback(message_callback, RoomMessageText)
receiver = asyncio.create_task(client.sync_forever(timeout=5))
if homeserver_online:
if plg_globals.settings["listen"]["old_messages"] is True:
receiver = asyncio.create_task(client.sync_forever(timeout=5))
else:
log_error("Sync failed: homeserver is down or your network disconnected with it.")
log_info("Use !!msync start after homeserver is running or your network restored.")
if resp is not None:
await client.sync(timeout=5, sync_filter=resp.filter_id)
client.add_event_callback(message_callback, RoomMessageText)
receiver = asyncio.create_task(client.sync_forever(timeout=5, sync_filter=resp.filter_id))
else:
await client.sync(timeout=5)
client.add_event_callback(message_callback, RoomMessageText)
receiver = asyncio.create_task(client.sync_forever(timeout=5))
else:
logger.error("Sync failed: homeserver is down or your network disconnected with it.", "Receiver")
logger.info("Use !!msync start after homeserver is running or your network restored.", "Receiver")

try:
await receiver
except asyncio.CancelledError:
log_warning(tr("on_receiver_cancelled"))
except Exception as e:
log_error(f"Receiver sync error: {e}")
try:
await receiver
except asyncio.CancelledError:
logger.warning(tr("on_receiver_cancelled"), "Receiver")
except Exception as e:
logger.error(f"Receiver sync error: {e}", "Receiver")
receiver.cancel()
finally:
if receiver:
receiver.cancel()
finally:
if receiver:
receiver.cancel()
try:
await receiver
except asyncio.CancelledError:
pass
client.stop_sync_forever()
if client is not None:
await client.close()

async def stop_sync():
Expand Down
5 changes: 1 addition & 4 deletions matrix_sync/client/reporter.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,14 @@
import matrix_sync.plg_globals as plg_globals

from . import get_homeserver
from .init import check_token
from ..utils import *
from ..utils.logger import *
from ..utils.token import getToken
from nio import AsyncClient


async def send_to_matrix(message) -> None:
client = AsyncClient(get_homeserver(plg_globals.config["homeserver"]))
token_vaild = await check_token()
if token_vaild:
if plg_globals.token_vaild:
user, token = await getToken()

client.user_id = plg_globals.config["user_id"]
Expand Down
32 changes: 21 additions & 11 deletions matrix_sync/commands/__init__.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import asyncio
import threading
import matrix_sync.logger.get_logger as get_logger
import matrix_sync.plg_globals as plg_globals

from mcdreforged.api.all import *
from ..client.reporter import send_to_matrix
from ..client.receiver import get_messages, stop_sync
from ..client import *
from ..utils import tr
from ..utils.logger import *
from ..utils import *
from .help import *


Expand All @@ -16,17 +16,23 @@
plg_globals.tLock = threading.Lock()

def start_sync():
logger = get_logger()
if not plg_globals.tLock.locked():
run_sync_task()
log_info(tr("on_sync_start"))
else:
log_warning(tr("on_sync_running"))
logger.warning(tr("on_sync_running"))

@new_thread('MatrixReceiver')
def run_sync_task():
logger = get_logger()
plg_globals.sync = True
with plg_globals.tLock:
asyncio.run(add_sync_task())
if plg_globals.token_vaild:
with plg_globals.tLock:
logger.info(tr("on_sync_start"))
asyncio.run(add_sync_task())
else:
logger.error(tr("token_mismatch"))
plg_globals.sync = False

async def add_sync_task():
await get_messages()
Expand Down Expand Up @@ -55,16 +61,20 @@ async def on_command_stop():

@builder.command("!!msync status")
def show_status():
log_info(f"Receiver: {plg_globals.sync}")
logger = get_logger()
logger.info(f"Receiver: {plg_globals.sync}")
if plg_globals.sync:
log_info(tr("sync_status.running"))
logger.info(tr("sync_status.running"))
else:
log_info(tr("sync_status.not_running"))
logger.info(tr("sync_status.not_running"))

@builder.command("!!msync send <message>")
def on_command_send(src: CommandSource, ctx: CommandContext):
matrix_reporter(ctx["message"])
src.reply(tr("on_send_command"))
if plg_globals.token_vaild:
matrix_reporter(ctx["message"])
src.reply(tr("on_send_command.sending"))
else:
src.reply(tr("on_send_command.failed") + ": " + tr("token_mismatch"))

@builder.command("!!msync reload")
def on_command_reload():
Expand Down
13 changes: 12 additions & 1 deletion matrix_sync/config/__init__.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,24 @@
import os
import matrix_sync.utils.tr as tr
import matrix_sync.plg_globals as plg_globals

from .default import *
from ..utils import *
from ..client.init import check_token
from mcdreforged.api.types import PluginServerInterface


async def load_config(server: PluginServerInterface):
plg_globals.config = server.load_config_simple('config.json', account_config)
if plg_globals.config == account_config:
server.unload_plugin(plgSelf.id)
plg_globals.settings = server.load_config_simple('settings.json', default_settings)
if plg_globals.settings["ver"] != "2.5.1":
plg_globals.settings = None
psi.logger.info(tr("settings_comp_check.failed"))
os.rename(f"{configDir}/settings.json", f"{configDir}/settings.json.bak")
plg_globals.settings = server.load_config_simple('settings.json', default_settings)
if not plg_globals.settings["log_style"]["mcdr"]:
psi.logger.info("Plugin MatrixSync will use its logger, with different format to MCDR.")
psi.logger.info("Plugin MatrixSync will use its logger, different with MCDR.")
if os.path.exists(f"{configDir}/token.json"):
plg_globals.token_vaild = await check_token()
5 changes: 3 additions & 2 deletions matrix_sync/config/default.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@
},
"log_style": {
"mcdr": False,
"debug": False
"debug": False,
"show_time": False
},
"ver": "2.5.0"
"ver": "2.5.1"
}
Loading

0 comments on commit dee1f20

Please sign in to comment.